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
精彩评论