Detect whether or not a specific attribute was valid on the model
Posted
by Sir Code-A-Lot
on Stack Overflow
See other posts from Stack Overflow
or by Sir Code-A-Lot
Published on 2010-06-15T10:51:47Z
Indexed on
2010/06/15
11:32 UTC
Read the original article
Hit count: 222
Having created my own validation attribute deriving from System.ComponentModel.DataAnnotations.ValidationAttribute, I wish to be able to detect from my controller, whether or not that specific attribute was valid on the model.
My setup:
public class MyModel
{
[Required]
[CustomValidation]
[SomeOtherValidation]
public string SomeProperty { get; set; }
}
public class CustomValidationAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
// Custom validation logic here
}
}
Now, how do I detect from the controller whether validation of CustomValidationAttribute succeeded or not?
I have been looking at the Exception property of ModelError in the ModelState, but I have no way of adding a custom exception to it from my CustomValidationAttribute.
Right now I have resorted to checking for a specific error message in the ModelState:
public ActionResult PostModel(MyModel model)
{
if(ModelState.Where(i => i.Value.Errors.Where((e => e.ErrorMessage == CustomValidationAttribute.SharedMessage)).Any()).Any())
DoSomeCustomStuff();
// The rest of the action here
}
And changed my CustomValidationAttribute to:
public class CustomValidationAttribute : ValidationAttribute
{
public static string SharedMessage = "CustomValidationAttribute error";
public override bool IsValid(object value)
{
ErrorMessage = SharedMessage;
// Custom validation logic here
}
}
I don't like relying on string matching, and this way the ErrorMessage property is kind of misused.
What are my options?
© Stack Overflow or respective owner