开发者

Detect whether or not a specific attribute was valid on the model

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)
{
  开发者_StackOverflow中文版  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?


I think it is meaningful to have a Enum named ExceptionType in the CustomValidationAttribute which clearly identifies the type of Exception raised.

In the controller we may check for the exceptionType and handle accordingly .

try
{

}
Catch(Exception e)
{
 Switch(e.ExceptionType)
 {
     case ExceptionType.Val1:

       // Handle accordingly  
       break;
 }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜