StringLength属性未验证为什么我的实现

时间:2019-05-31 15:19:10

标签: c# validation data-annotations

我曾经使用This使用属性来实现自己的数据验证。但是,当我运行单元测试时,它会失败

单元测试:

      [TestMethod]
      public void CheckAttributes_StringLengthAttribute_ShouldAddErrorIfToManyCharacters()
      {
           //Arrange
           _model.FirstName = "asdf";
           _model.LastName = "abcdefghijklmnopqrstuvwxyz";

           //Act
           _abstractModelValidation.CheckMyAttributes(_model);

           //Assert
           Assert.IsFalse(_abstractModelValidation.IsValid);
      }

仅供参考_abstractModelValidation.IsValid = Errors.Any();

我对以上链接的实现:

      protected void CheckAttributes(T model)
      {
           var context = new ValidationContext(model, null, null);
           var results = new List<ValidationResult>();

           var isValid = Validator.TryValidateObject(model, context, results);
           if (!isValid)
           {
                foreach (var validationResult in results)
                {
                     foreach (var memberName in validationResult.MemberNames)
                     {
                          AddError(memberName, validationResult.ErrorMessage);
                     }
                }
           }
      }

模型类:

 public class ValidatorModel
 {
      public int Id { get; set; }

      [StringLength(25), Required]
      public string FirstName { get; set; }

      [StringLength(9, MinimumLength = 9)]
      public string LastName { get; set; }

 }

仅供参考,[Required]确实会添加错误

有人可以告诉我我做错了什么吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

我已经弄清楚了我的问题;我希望这对其他人有帮助!

问题在于存在另一个重载,该重载是布尔属性validateAllProperties。改变成真的,做到了!

      protected void CheckAttributes(T model)
      {
           var context = new ValidationContext(model, null, null);
           var results = new List<ValidationResult>();

           var isValid = Validator.TryValidateObject(model, context, results, true);
           if (!isValid)
           {
                foreach (var validationResult in results)
                {
                     foreach (var memberName in validationResult.MemberNames)
                     {
                          AddError(memberName, validationResult.ErrorMessage);
                     }
                }
           }
      }