Question

There is a method in Parsley extend .js to error check for incorrect dates. eg: M/D/YY

I would like to alter this to only check for month and year. eg: MM/YYYY

 americandate: function ( val, elem, self) {
        if(!/^([01]?[0-9])[\.\/-]([0-3]?[0-9])[\.\/-]([0-9]{4}|[0-9]{2})$/.test(val)) {
            return false;
        }
        var parts = val.split(/[.\/-]+/);
        var day = parseInt(parts[1], 10);
        var month = parseInt(parts[0], 10);
        var year = parseInt(parts[2], 10);
        if(year == 0 || month == 0 || month > 12) {
          return false;
        }
        var monthLength = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
        if(year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)) {
          monthLength[1] = 29;
        }
        return day > 0 && day <= monthLength[month - 1];
      }
Était-ce utile?

La solution

The complexity of your function is designed to enforce the correct number of days in month.

For all dates (in recent history) require 1-12 in the months field and 2 or four digits in the years field. Why not just write a simple regular expression to validate the date is composed of the proper characters.

\b(1[12]|0?[1-9])[.\/-]([0-9]{2}?[0-9]{2})\b

enter image description here

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top