1

I am having an issue with a regular expression to validate my date format i.e. dd/mm/yyyy.

Basically I build the client side Javascript for checking the data format from code behind like shown below

public static string CalendarJS()
{
  string sCalendarJS = string.Empty;
  sCalendarJS = "<script type=\"text/javascript\">" +
             "function checkDate(){" +
             "var sDate = document.getElementById(\"ddlDays\").value;" +
             "var sMonth = document.getElementById(\"ddlMonth\").value;" +
             "var sYear = document.getElementById(\"ddlYear\").value;" +
             "var cDate = sDate + \"/\" + sMonth + \"/\" + sYear;" +
             "validatedate(cDate);" +
             "}" +
             "function validatedate(input){" +
             "var validformat= '^\\d{2}\\/\\d{2}\\/\\d{4}$';" +                  
             "var returnval=false;" +
             "if (!validformat.test(input.value))" +
             "alert(\"Invalid Date Format. Please correct and submit again.\");" +
             "else{" +
             "var monthfield=input.value.split(\"/\")[0];" +
             "var dayfield=input.value.split(\"/\")[1];" +
             "var yearfield=input.value.split(\"/\")[2];" +
             "var dayobj = new Date(yearfield, monthfield-1, dayfield);" +
             "if ((dayobj.getMonth()+1!=monthfield)||(dayobj.getDate()!=dayfield)||(dayobj.getFullYear()!=yearfield))" +
             "alert(\"Invalid Day, Month, or Year range detected. Please correct and submit again.\");" +
             "else" +
             "returnval=true;" +
             "}" +
             "if (returnval=false) input.select();" +                 
             "return returnval;" +                 
             "}" +
             "</script>";

  return sCalendarJS;
 }

I call the above method on click event of submit button by passing in the date parameters as e.g. 01/01/2016.

However it seems to fail at 'Invalid Date format'. The regex for the date validation is ^\d{2}/\d{2}/\d{4}$ and I have tested the regex on here http://www.regular-expressions.info/javascriptexample.html and it passes fine. However, am not sure if I am passing it correcting?

I had to put extra backslashes in the regex as it was complaining about about "unrecognised escape sequence" in the expression. I am not sure if this is the correct way to fix this?

Solution I removed the regex for the date format validation as I had dropdownlist in place for the day, month and year fields. So none of these were input hence didnt require validation as I was setting the format. Only thing required was to check for leap year and day range for given month.

Anyhow it doesn't solve the issue for the regex but does give a solution for the other checks

string sCalendarJS = string.Empty;
sCalendarJS = @"<script type='text/javascript'>
                function checkDate(){
                    var sDate = document.getElementById('ddlDays').value;
                    var sMonth = document.getElementById('ddlMonth').value;
                    var sYear = document.getElementById('ddlYear').value;
                    var cDate = sMonth + '/' + sDate + '/' + sYear;
                    if (validatedate(cDate) == true) return true;                                            
                }
                function validatedate(input){
                     var returnval=false;
                     var monthfield=input.split('/')[0];                         
                     var dayfield=input.split('/')[1];
                     var yearfield=input.split('/')[2];                         
                     var dayobj = new Date(yearfield, monthfield-1,     dayfield);                         
                     if ((dayobj.getMonth()+1!=monthfield)||(dayobj.getDate()!=dayfield)||(dayobj.getFullYear()!=yearfield))
                         alert('Invalid Day, Month, or Year range detected. Please correct and submit again.');                             
                     else
                         returnval=true;                                                                              
                     return returnval;                         
                    }
              </script>";

Hope this helps?

KJSR
  • 1,679
  • 6
  • 28
  • 51
  • 3
    `"var validformat= '^\\d{2}\\/\\d{2}\\/\\d{4}$';"` --> `"var validformat= /^\d{2}\/\d{2}\/\d{4}$/;"`. Please check if it works after this change. – Wiktor Stribiżew Feb 29 '16 at 15:57
  • Hi Wiktor the suggestion doesn't work as it complains about unrecognised escape sequence after `/^\d` as mentioned in the OP. – KJSR Feb 29 '16 at 16:04
  • 2
    Yes, because you'd need to declare that using a verbatim string literal. Well, just changing `'^\\d{2}\\/\\d{2}\\/\\d{4}$';` to `/^\\d{2}\\/\\d{2}\\/\\d{4}$/;` won't help. You have lots of issues in this JS code. Like `elsereturnval=true;`. I suggest you should take this JS function out, use it at [jsfiddle.net](http://jsfiddle.net) to check against a sample input you have, fix, and then re-format as a string for your C# method. – Wiktor Stribiżew Feb 29 '16 at 16:06
  • Thanks Wiktor for the suggestion. I got the original JS from here http://www.javascriptkit.com/script/script2/validatedate.shtml if it helps? Works fine in its natural form. – KJSR Feb 29 '16 at 16:10
  • 1
    Does this help ? http://stackoverflow.com/questions/276479/javascript-how-to-validate-dates-in-format-mm-dd-yyyy – Iceman Feb 29 '16 at 16:42

1 Answers1

1

Two things: (1) C# has use raw string literal by prefixing the it with an @ (can't remember from which version). (2) Javascript allows both single and double quote as string delimiter. Use single quote to avoid having to escape from C#.

Try this:

sCalendarJS = @"<script type='text/javascript'>
    function checkDate(){
        var sDate = document.getElementById('ddlDays').value;
        var sMonth = document.getElementById('ddlMonth').value;
        var sYear = document.getElementById('ddlYear').value;
        var cDate = sDate + '/' + sMonth + '/' + sYear;
        validatedate(cDate);
    }
    function validatedate(input){
        var validformat= '^\\d{2}\\/\\d{2}\\/\\d{4}$';
        var returnval=false;
        if (!validformat.test(input.value))
            alert('Invalid Date Format. Please correct and submit again.');
        else {
            var monthfield=input.value.split('/')[0];
            var dayfield=input.value.split('/')[1];
            var yearfield=input.value.split('/')[2];
            var dayobj = new Date(yearfield, monthfield-1, dayfield);
            if ((dayobj.getMonth()+1!=monthfield)||(dayobj.getDate()!=dayfield)||(dayobj.getFullYear()!=yearfield))
                alert('Invalid Day, Month, or Year range detected. Please correct and submit again.');
            else
                returnval=true;
        }
        if (returnval=false) input.select();
            return returnval;
        }
        </script>";
Code Different
  • 90,614
  • 16
  • 144
  • 163
  • FYI: *raw string literal* is in fact called *verbatim string literal*. – Wiktor Stribiżew Mar 01 '16 at 07:46
  • Thanks **Code Different** for the solution however, it is still failing on regex validation. It comes back as Invalid Date Format. I even changed the regex to `var validformat= /^\d{2}\/\d{2}\/\d{4}$/;` and it still fails to validate? – KJSR Mar 01 '16 at 10:29
  • Ok I resolved the issue by removing the date format validation as it wasn't required since users have to select the day, month and year via the dropdown list. Only thing required was to check for leap year and validate the date range. Posting the solution above. However this doesn't solve the regex issue. – KJSR Mar 01 '16 at 11:44