Search code examples
javascriptasp.netregexdate-formatserver-side-validation

Date Format validation Giving an Error


I have used date format expression in my project. I have used it in Javascript it's working fine. But while i am using it at Server side it gives me an error that Unrecognized Escape Sequence. My format is as below. Even i tried Regex. but still not working. My format is as below.

  protected void txt_duedate_validate_server(object source, ServerValidateEventArgs args)
{
    string duedate = txtduedate.Text.Trim();
    if (duedate == string.Empty || duedate == "Due Date")
    {
        args.IsValid = false;
        return;

    }
    else
    {
        string fromdatePat =  "/^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((19|[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))))$/;";
        Regex re = new Regex(fromdatePat);

        string compare=srqstdate.match(fromdatePat);
        if(compare==null)
        {
            args.IsValid = false; 
            return false;
    }
    }

}

Solution

  • Your code looks like C#. Edit your regular expression taken from JavaScript: Omit the leading and trailing slashes (and semicolon) (/.../;). Remove escaping from remaining slashes (/ instead of \/). Use a verbatim string literal (@"...") so you do not need to add extra escaping.

    string fromdatePat = @"^(((0[1-9]|[12]\d|3[01])/(0[13578]|1[02])/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])/02/((19|[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))))";
    Regex re = new Regex(fromdatePat);
    if (!re.IsMatch(srqstdate)) { args.IsValid = false; }