Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 288
marcus Avatar asked Sep 23 '12 13:09

marcus


People also ask

How to display Validation error message in MVC?

You can use the standard ASP.NET MVC ValidationSummary method to render a placeholder for the list of validation error messages. The ValidationSummary() method returns an unordered list (ul element) of validation messages that are in the ModelStateDictionary object.

How do I create a custom validation attribute?

To create a custom validation attributeIn Solution Explorer, right-click the App_Code folder, and then click Add New Item. Under Add New Item, click Class. In the Name box, enter the name of the custom validation attribute class. You can use any name that is not already being used.

What does ValidationMessageFor do?

ValidationMessageFor<TModel,TProperty>(HtmlHelper<TModel>, Expression<Func<TModel,TProperty>>, String) Returns the HTML markup for a validation-error message for each data field that is represented by the specified expression, using the specified message.

What is ValidationAttribute?

ValidationAttribute class is included in the DataAnnotations namespace. It helps you to validate the model data received from the user. It gives you many inbuilt validation attributes like StringLength, Required, DataType for validating the model.


2 Answers

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.

like image 55
Kirby Avatar answered Sep 28 '22 08:09

Kirby


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.

like image 31
Darin Dimitrov Avatar answered Sep 28 '22 09:09

Darin Dimitrov