Receive error message when using custom validation attribute

I am using a CustomValidationAttribute attribute 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 an error message from a custom validation attribute?

+4
source share
4 answers

There is no reliable way to get the error message from an attribute. Alternatively, you can write your own 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 displayed from the user verification attribute.

+5
source

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

The responder wants to use CustomValidationAttribute and pass the error message using the ErrorMessage property.

If you want your static method to use the error message that you provided when registering your property, you also return:

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

CustomValidationAttribute overrides FormatErrorMessage its base class and performs a conditional check on string.IsNullOrEmpty .

+4
source

You can look at the following publication to get some ideas on how to do what you want to do (they use JS):

Custom text validation error via javascript?

Hope this helps.

0
source

The only way I found work: to check the model using the post back method with TryValidateObject, and if it does not work, show the model again - then an error will appear.

  [HttpPost] public ActionResult Standard(Standard model) { var valContext = new ValidationContext(model, null, null); var valResults = new List<ValidationResult>();; bool b = Validator.TryValidateObject(model, valContext, valResults, true); if(!b) return View(model); ... 
0
source

Source: https://habr.com/ru/post/1435748/


All Articles