Question

I have a custom ValidationAttribute in my ASP.NET MVC3 project which has two conditions which need to be met. It works well but I would like to let the user now which validation rule has been broken by returning a customised error message.

With the method I am using (inherit error message from base class) I know I can not change the value of the _defaultError constant after it has been initialised, so....

How do I return different error messages depending on which condition was not met?

Here is my ValidationAttribute code:

public class DateValidationAttribute :ValidationAttribute
{
    public DateValidationAttribute() 
        : base(_defaultError)
    {

    }

    private const string _defaultError = "{0} [here is my generic error message]";

    public override bool IsValid(object value)
    {
        DateTime val = (DateTime)value;

        if (val > Convert.ToDateTime("13:30:00 PM"))
        {
            //This is where I'd like to set the error message
            //_defaultError = "{0} can not be after 1:30pm";
            return false;
        }
        else if (DateTime.Now.AddHours(1).Ticks > val.Ticks)
        {
            //This is where I'd like to set the error message
            //_defaultError = "{0} must be at least 1 hour from now";
           return false;
        }
        else
        {
            return true;
        }

    }
}
Was it helpful?

Solution

I could advise you to create two different implementation of DateValidator class, each having different message. This is also in line with SRP as you just keep the relevant validation information in each validator separate.

public class AfternoonDateValidationAttribute : ValidationAttribute
{
   // Your validation logic and message here
}

public class TimeValidationAttribute : ValidationAttribute
{
   // Your validation logic and message here
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top