diff --git a/Falcon.SugarApi.Test/ModelValidationTest.cs b/Falcon.SugarApi.Test/ModelValidationTest.cs new file mode 100644 index 0000000..5b3cff9 --- /dev/null +++ b/Falcon.SugarApi.Test/ModelValidationTest.cs @@ -0,0 +1,76 @@ +using Falcon.SugarApi.ModelValidation; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; + +namespace Falcon.SugarApi.Test +{ + /// + /// Json序列化测试 + /// + [TestClass] + public class ModelValidationTest + { + [TestMethod] + public void ValidateTest() { + TestModel model; + List results; + bool r; + + model = new TestModel { + Age = "30", + Name = "Tom", + }; + r = model.TryModelValidation(out results); + Assert.IsTrue(r); + Assert.IsTrue(results != null); + Assert.IsTrue(results.Count == 0); + + model = new TestModel { + Age = "60", + }; + r = model.TryModelValidation(out results); + Assert.IsFalse(r); + Assert.IsTrue(results.Count == 2); + + model = new TestModel { + MaxLength = "111111111111111111", + Name = "Tom", + Age = "30", + }; + r = model.TryModelValidation(out results); + Assert.IsFalse(r); + Assert.IsTrue(results.Count == 1); + + model = new TestModel { + Name = "abc", + Age = "20", + IsIntProp = "abc", + MaxLength = "1", + }; + r = model.TryModelValidation(out results); + Assert.IsFalse(r); + Assert.IsTrue(results.Count == 1); + Assert.IsTrue(results.First().MemberNames.First() == "IsIntProp"); + } + /// + /// 测试用模型 + /// + public class TestModel + { + [Required] + public string Name { get; set; } + + [Range(10, 50)] + public string Age { get; set; } + + [MaxLength(3)] + public string MaxLength { get; set; } + + [IsInt] + public string IsIntProp { get; set; } = "123"; + } + } +} diff --git a/Falcon.SugarApi/ModelValidation/ObjectValidateExtend.cs b/Falcon.SugarApi/ModelValidation/ObjectValidateExtend.cs new file mode 100644 index 0000000..34dd8c2 --- /dev/null +++ b/Falcon.SugarApi/ModelValidation/ObjectValidateExtend.cs @@ -0,0 +1,23 @@ +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; + +namespace Falcon.SugarApi.ModelValidation +{ + /// + /// 扩展对象验证方法 + /// + public static class ObjectValidateExtend + { + /// + /// 尝试执行对象验证,返回验证结果 + /// + /// 要验证的模型 + /// 验证结果 + /// 通过验证True,否则False + public static bool TryModelValidation(this object model, out List results) { + var context = new ValidationContext(model); + results = new List(); + return Validator.TryValidateObject(model, context, results, true); + } + } +}