views:

163

answers:

1

Right now...the dateISO method is as follows:

dateISO: function(value, element) {
  return this.optional(element) || /^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(value);
 },

but ive noticed that when a user enters something like 1991-99-99 it sees it as a "valid date" when it obviously is not. How would i change this code to have it check if the month is 01-12 and the date is 1-31?

A: 

In general, good date validation is very difficult. From Time and the Art of Living (as quoted in the GNU date documentation), I quote Robert Grudin:

Our units of temporal measurement, from seconds on up to months, are so complicated, asymmetrical and disjunctive so as to make coherent mental reckoning in time all but impossible. Indeed, had some tyrannical god contrived to enslave our minds to time, to make it all but impossible for us to escape subjection to sodden routines and unpleasant surprises, he could hardly have done better than handing down our present system.

However, if you only want to accept dates in that YYYY-MM-DD format, the work gets a little easier. How about something like:

dateISO: function(value, element) {
  if (this.optional(element)) return true;
  var regexp = new RegExp('^\d{4}[\/-](\d{1,2})[\/-](\d{1,2})$');
  var matches = regexp.exec(value);
  if (!matches) return false;
  if (matches[2] > 31) return false;

  if (matches[1] == 2 && matches[2] > 28) return false;
  if ((matches[1] == 1 || matches[1] == 3 || matches[1] == 5 || matches[1] == 7 || matches[1] == 8 || matches[1] == 10 || matches[1] == 12) && matches[2] > 30) return false;

  return true;
},
VoteyDisciple
i get an error on the line "if(!matches[0]) return false";Message: '0' is null or not an object
Ian McCullough
Good point. It should simply be testing the result of `.exec()`.
VoteyDisciple
now it is always returning "false"
Ian McCullough
This code doesnt work, but this does:http://stackoverflow.com/questions/1301466/whats-wrong-with-this-jquery-validation-code-regexp-execvalue
Ian McCullough