1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
- using System.Linq;
- using System.Text;
- namespace TEAMModelOS.SDK
- {
- public static class ValidatorHelper
- {
- public static ValidResult Valid(this Object obj) {
- ValidResult result = new ValidResult();
- var list = obj as IEnumerable;
- if (list != null)
- {
- foreach (var item in list)
- {
- var validationContext = new ValidationContext(item);
- var validationResults = new List<ValidationResult>();
- var isItemValid = Validator.TryValidateObject(item, validationContext, validationResults, true);
- result.isVaild = isItemValid;
- }
- }
- else {
- try
- {
- var context = new ValidationContext(obj, null, null);
- var results = new List<ValidationResult>();
- if (Validator.TryValidateObject(obj, context, results, true))
- {
- result.isVaild = true;
- }
- else
- {
- List<(string msg, string name)> error = new List<(string msg, string name)>();
- foreach (var validationResult in results)
- {
- if (validationResult.MemberNames != null && validationResult.MemberNames.Count() > 0)
- {
- validationResult.MemberNames.ToList().ForEach(x => {
- error.Add((validationResult.ErrorMessage, x));
- });
- }
- }
- result.errors = new Dictionary<string, IEnumerable<string>>();
- error.GroupBy(x => x.name).ToList().ForEach(z => {
- result.errors.Add(z.Key, z.ToList().Select(x => x.msg));
- });
- }
- }
- catch (Exception ex)
- {
- result.isVaild = false;
- result.errors = new Dictionary<string, IEnumerable<string>>();
- result.errors.Add("InternalError", new List<string> { ex.Message });
- }
- }
-
- return result;
- }
-
- }
- public class ValidResult
- {
- public string traceId { get; set; } = Guid.NewGuid().ToString();
- public string type { get; set; } = "https://tools.ietf.org/html/rfc7231#section-6.5.1";
- public string title { get; set; } = "One or more validation errors occurred.";
- public int status { get; set; } = 400;
- public bool isVaild { get; set; }
- public Dictionary<string, IEnumerable<string>> errors { get; set; }
- }
- }
|