views:

850

answers:

3
[Required(ErrorMessage = "Date is required")]
[RegularExpression(@"^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((1[6-9]|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((1[6-9]|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((1[6-9]|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$", ErrorMessage="Date is not valid must be like (dd/mm/jjjj)")]
public DateTime Startdate{ get; set;}

The client-side validation works perfectly. So it seems that JavaScript can successfully understand my regular expression. But when I do a postback, and the modelstate.Isvalid() gets called.

My date isn't valid anymore. So I'm guessing that when .NET performs the matching with the regEx it doesn't match.

My question: Why does this regular expression match on the client side but not on the server side?

+1  A: 

I think that if you want to check regular expression, you should use:

public string Startdate{ get; set;}

and then convert it to DateTime on server side, after model binding. You know that date has to be provided in specific format, but model binder is not that smart and throws an error. If you have DateTime after model binding, there is no sense in checking it by regular expression, doesn't it? Model binding comes first and then validation.

LukLed
A: 

Is it possible that the client-side validation rules aren't actually being applied? Have you checked that the required attribute works as expected? You should be able to use firebug to double-check that the regular expression is the same on the server side, that all values are as expected etc.

Also - it could be that the inserted value passes the regex, but still can't be converted to a datetime by the model binder - that would also produce a model error.

I haven't checked your regex to see what it really does, but if you're trying to verify that the input is a valid date, use the DataTypeAttribute instead.

Tomas Lycken
I tried the datatypeAttribute, It doesn't validate at all. I also read on the internet that it is not made for validation.
wh0emPah
+2  A: 

This is becouse when you do postback databinder goes first, and it could not parse value to DateTime. By the way it's not a good idea to put RegularExpression attribute on DateTime class. It has following code

public override bool IsValid(object value)
{
    string str = Convert.ToString(value, CultureInfo.CurrentCulture);
    if (string.IsNullOrEmpty(str))
    {
        return true;
    }
    Match match = this.Regex.Match(str);
    return ((match.Success && (match.Index == 0)) && (match.Length == str.Length));
}

so Convert.ToString(value, CultureInfo.CurrentCulture) will never match your regex, becouse it will have time part too.

You should better use String instead of datetime.

er-v