StringLengthAttribute似乎不起作用

Mik*_*ike 9 validation ria data-annotations

这是我的带有数据注释的Test类:

class Test
{
  [Required, StringLength(10)]
  public string MyProperty { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

这是我的控制台测试程序:

class Program
{
  static void Main(string[] args)
  {
    var test = new Test {
      MyProperty = "this is way more than 10 characters and should fail."
    };

    var context = new ValidationContext(test, null, null);

    // No exception here! (why not?)
    Validator.ValidateObject(test, context);

    test.MyProperty = null;

    // Exception here, as expected
    Validator.ValidateObject(test, context);
  }
}
Run Code Online (Sandbox Code Playgroud)

出于某种原因,当字符串长度太长时,我没有得到验证异常.当我将属性设置为null并重新验证时,我确实得到了验证异常(如预期的那样).我的字符串长度注释没有被强制执行的任何想法?

Mik*_*ike 22

这有点不直观,但正在改变

Validator.ValidateObject(test, context);
Run Code Online (Sandbox Code Playgroud)

Validator.ValidateObject(test, context, true);
Run Code Online (Sandbox Code Playgroud)

解决了这个问题.第三个论点是bool validateAllProperties.我不确定为什么该[Required]属性以前被强制执行而[StringLength]不是,但至少它现在都有效.