简体   繁体   中英

Regex Date Format Validation

I am having an issue with a regular expression to validate my date format ie 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 eg 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?

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>";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM