问题
I have custom validation attribute such as this:
public class MyCustomAttribute : ValidationAttribute {
protected override ValidationResult IsValid(object value, ValidationContext validationContext) {
if ((int)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?
回答1:
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)
来源:https://stackoverflow.com/questions/5408658/validation-context-is-always-null