-2

I am trying to validate date format in yyyy-dd-mm. I am trying this by below validator matod. It is validating date by using /^(\d{4})(-)(\d{1,2})(-)(\d{1,2})$/ regex. When I am trying to validate it using /^((?:19|20)\d\d)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])$/ it is working wrong.

jQuery.validator.addMethod(
"validateDateFormat",
function(value, element) {
    var currVal = value;
    if (currVal != '') {
        var rxDatePattern = /^(\d{4})(-)(\d{1,2})(-)(\d{1,2})$/;
        //var rxDatePattern = /^((?:19|20)\d\d)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])$/;
        var dtArray = currVal.match(rxDatePattern);
        if (dtArray == null){

               return false;
        }
        dtYear = dtArray[1];
        dtMonth= dtArray[3];
        dtDay = dtArray[5];

        if (dtMonth < 1 || dtMonth > 12)
            return false;
        else if (dtDay < 1 || dtDay > 31)
            return false;
        else if ((dtMonth == 4 || dtMonth == 6 || dtMonth == 9 || dtMonth == 11) && dtDay == 31)
            return false;
        else if (dtMonth == 2)
        {
            var isleap = (dtYear % 4 == 0 && (dtYear % 100 != 0 || dtYear % 400 == 0));
            if (dtDay > 29 || (dtDay == 29 && !isleap))
                    return false;
        }
    }

    return true;
},
     "Please enter a valid date, date format should be (yyyy-mm-dd)."
);

What I am trying to validate here:

  1. Only int and "-" allowed.
  2. Dates are allowed only in the YYYY-MM-DD format.
  3. YYYY should be greater than 1900 and should be 4 int.
  4. MM should be between 01 to 12 and should be 2 char.
  5. DD should be between 01 to 31 and should be 2 char.
Roopendra
  • 7,674
  • 16
  • 65
  • 92
  • Your regex seems valid for me.. but it will also accept invalid dates (2000-02-31)... maybe this will help you: http://stackoverflow.com/questions/8098202/javascript-detecting-valid-dates – Marc Jun 10 '13 at 06:25
  • Please also specify reason of down-vote. – Roopendra Jun 10 '13 at 09:04
  • Your question is somehow unspecific... "working wrong" could be anything. Do wrong dates get accepted? Do right dates get not accepted? Examples? – Marc Jun 10 '13 at 14:15
  • I have already handle for leap year. I have posted here only small piece of code in which I need to help. I have already solve this problem. But people Down-vote it after 7days posting of this question. Great !!!.. – Roopendra Jun 10 '13 at 17:33
  • I had missed proper grouping in regex. After regex correction everything is working as per my requirement `/^((?:19|20)\d\d)(-)(0[1-9]|1[012])(-)(0[1-9]|[12][0-9]|3[01])$/` . – Roopendra Jun 10 '13 at 17:41

1 Answers1

2

Regexes are not designed to do numerical processing.

Keep it simple. Use regex to match against the basic pattern and extract the relevant tokens, then apply your numerical and other business rules on the numbers you get. You'll thank yourself when you need to maintain this later.

Platinum Azure
  • 45,269
  • 12
  • 110
  • 134