Jignesh J
Jignesh J

Reputation: 11

ASP.Net MVC 2.0 Date validation not working

I am trying to validate date value in dd/mm/yyyy format.I am getting error message even if I enter the date in correct format.

Here is my Code :

[Required(ErrorMessage = "Required Field.")]            
[RegularExpression(@"^((0[1-9])|([1-2][0-9])|3[0-1])\/((0[1-9])|(1[0-2]))\/[0-9]{4}$",ErrorMessage="Please enter in dd/mm/yyyy")]
[DataType(DataType.Date,ErrorMessage="Please enter date.")]
public DateTime BeginningDate { get; set; }

Upvotes: 1

Views: 2031

Answers (2)

karaxuna
karaxuna

Reputation: 26930

public class DateRegexAttribute : RegularExpressionAttribute, IClientValidatable
    {
    public DateRegexAttribute(string pattern)
        : base(pattern)
    {
    }

    public override bool IsValid(object value)
    {
        DateTime date;
        try
        {
            date = (DateTime) value;
        }
        catch
        {
            return false;
        }

        var input = date.Date.ToShortDateString();

        Match match = Regex.Match(input, Pattern, RegexOptions.IgnoreCase);

        return match.Success;
    }


    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRegexRule(ErrorMessageString, Pattern);
        return new[] { rule };
    }
}

Upvotes: 0

LukLed
LukLed

Reputation: 31842

The error message you get comes from model binder, it has nothing in common with your attributes. I think, that if you want to check regular expression, you should use:

public string BeginningDate { get; set;}

and then convert it to DateTime by yourself, after model binding. You know that date has to be provided in specific format, but model binder is not that smart, uses web.config/server setting, and throws an error. Checking DateTime type by regular expression doesn't make sense, because it is already DateTime, not string. Model binding comes first and then validation.

Upvotes: 1

Related Questions