CustomValidationAttribute specifed方法不会被调用 [英] CustomValidationAttribute specifed method not being called

查看:441
本文介绍了CustomValidationAttribute specifed方法不会被调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是System.ComponentModel.DataAnnotations.CustomValidationAttribute来验证我的POCO类之一,当我试图单元测试,它甚至没有调用验证方法。

I'm using the System.ComponentModel.DataAnnotations.CustomValidationAttribute to validate one of my POCO classes and when I try to unit test it, it's not even calling the validation method.

public class Foo
{
  [Required]
  public string SomethingRequired { get; set }
  [CustomValidation(typeof(Foo), "ValidateBar")]
  public int? Bar { get; set; }
  public string Fark { get; set; }

  public static ValidationResult ValidateBar(int? v, ValidationContext context) {
    var foo = context.ObjectInstance as Foo;
    if(!v.HasValue && String.IsNullOrWhiteSpace(foo.Fark)) {
      return new ValidationResult("Either Bar or Fark must have something in them.");
    }
    return ValidationResult.Success;
  }
}



但是当我尝试对其进行验证:

but when I try to validate it:

var foo = new Foo { 
  SomethingRequired = "okay"
};
var validationContext = new ValidationContext(foo, null, null);
var validationResults = new List<ValidationResult>();
bool isvalid = Validator.TryValidateObject(foo, validationContext, validationResults);
Assert.IsFalse(isvalid); //FAIL!!! It's valid when it shouldn't be!



它甚至从来没有步入自定义验证方法。是什么给了?

It never even steps into the custom validation method. What gives?

推荐答案

尝试使用,需要一个布尔值,指定如果所有属性都应该被验证过载。对最后一个参数传递true。

Try using the overload that takes a bool that specifies if all properties should be validated. Pass true for the last parameter.

public static bool TryValidateObject(
    Object instance,
    ValidationContext validationContext,
    ICollection<ValidationResult> validationResults,
    bool validateAllProperties
)

如果你传递虚假或省略validateAllProperties,只有将RequiredAttribute标签进行检查。
这里是 MSDN文档

If you pass false or omit the validateAllProperties, only the RequiredAttribute will be checked. Here is the MSDN documentation.

这篇关于CustomValidationAttribute specifed方法不会被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆