Get error message when using custom validation attribute

marcus picture marcus · Sep 23, 2012 · Viewed 12.1k times · Source

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?

Answer

Kirby picture Kirby · Oct 22, 2014

I know this is a little of an old post, but I will provide an better answer to the question.

The asker wants to use the CustomValidationAttribute and pass in an error message using the ErrorMessage property.

If you would like your static method to use the error message that you provided when decorating your property, then you return either:

new ValidationResult(string.Empty) or ValidationResult("") or ValidationResult(null).

The CustomValidationAttribute overrides the FormatErrorMessage of its base class and does a conditional check for string.IsNullOrEmpty.