开发者

Validation Context is always NULL?

开发者 https://www.devze.com 2023-02-19 11:34 出处:网络
I have custom validation attribute such as this: public class MyCustomAttribute : ValidationAttribute {

I have custom validation attribute such as this:

    public class MyCustomAttribute : ValidationAttribute {
    protected override ValidationResult IsValid(object value, ValidationContext validationContext) {
        if ((i开发者_Go百科nt)value == 100) {
            // do some checking to validate & return ValidationResult accordingly

        } else return ValidationResult.Success;
    }
}

In usage like this:

    [DisplayName("My Custom Property")]
    [MyCustom(ErrorMessage = "ERROR!!!")]
    public int? MyCustomProperty { get; set; }

My question is: why is it that inside MyCustomAttribute, within the IsValid method, validationContext is always NULL? Is there anything special I need to set to get it not to be NULL?


if you use

ValidationResult IsValid(object value, ValidationContext validationContext)

to check if data is valid you have to use

v.GetValidationResult(propertyValue,new ValidationContext(this))!= ValidationResult.Success

instead of

 v.IsValid(propertyValue)


you must override RequiresValidationContext


public override bool RequiresValidationContext => true;

it will work

0

精彩评论

暂无评论...
验证码 换一张
取 消