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?
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.
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.
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.
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.
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With