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(); var isItemValid = Validator.TryValidateObject(item, validationContext, validationResults, true); result.isVaild = isItemValid; } } else { try { var context = new ValidationContext(obj, null, null); var results = new List(); 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>(); 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>(); result.errors.Add("InternalError", new List { 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> errors { get; set; } } }