views:

27

answers:

1

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?

A: 

Hi,

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;
 }
}
vijaysylvester
Hmm, I don't see how that would work with modelbinding. The exception would occur before the action is invoked.I'm also not sure if it is a good idea to just base the design on throwing exceptions in the CustomValidationAttribute.IsValid method. I mean, if what I'm validating with it isn't valid, I should simply return false.
Sir Code-A-Lot