Search code examples
c#asp.net-mvcasp.net-mvc-3data-annotationscustomvalidator

Get error message when using custom validation attribute


I'm using the CustomValidationAttribute like this

[CustomValidation(typeof(MyValidator),"Validate",ErrorMessage = "Foo")]

And my validator contains this code

public class MyValidator {
    public static ValidationResult Validate(TestProperty testProperty, ValidationContext validationContext) {
        if (string.IsNullOrEmpty(testProperty.Name)) {
            return new ValidationResult(""); <-- how can I get the error message  from the custom validation attribute? 
        }
        return ValidationResult.Success;
    }
}

So how can I get the error message from the custom validation attribute?


Solution

  • There's no reliable way to get the error message from the attribute. Alternatively you could write a custom validation attribute:

    [MyValidator(ErrorMessage = "Foo")]
    public TestProperty SomeProperty { get; set; }
    

    like this:

    public class MyValidatorAttribute : ValidationAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var testProperty = (TestProperty)value;
            if (testProperty == null || string.IsNullOrEmpty(testProperty.Name))
            {
                return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
            }
    
            return null;
        }
    }
    

    In this case the error message will be inferred from the custom validation attribute.