2

I was referring this link and as I do not have 50 reputation I am not allowed to comment in the answer so posting this question. I did not get the statement where you can see a month is subtracted from months. This can be simple one but could anyone please clarify on this?

var m = matches1 - 1; ?

function isValidDate(date)
{
    var matches = /^(\d{2})[-\/](\d{2})[-\/](\d{4})$/.exec(date);
    if (matches == null) return false;
    var d = matches[2];
    var m = matches[1] - 1;
    var y = matches[3];
    var composedDate = new Date(y, m, d);
    return composedDate.getDate() == d &&
            composedDate.getMonth() == m &&
            composedDate.getFullYear() == y;
}
Community
  • 1
  • 1
Ashish
  • 246
  • 1
  • 2
  • 12
  • 1
    Possible duplicate of [Javascript: how to validate dates in format MM-DD-YYYY?](http://stackoverflow.com/questions/276479/javascript-how-to-validate-dates-in-format-mm-dd-yyyy) – akashchandrakar Feb 12 '16 at 06:49
  • Hi aksam, I have already mentioned that link in question and stated the reason why I had to post this question. – Ashish Feb 12 '16 at 07:17

2 Answers2

1

var m = matches1 - 1; ?

months index starts from 0.

So while you think Jan is 1, it is actually 0 when you do date.getMonth().

Which is why when you get 1 from a date-string, you need to make it 0 before setting it to a date object.

gurvinder372
  • 66,980
  • 10
  • 72
  • 94
0

In the spirt of the question, the validation function is way overdone. Only the month needs to be checked since if either the day or month is out of bounds, the month of the generated date will change.

Also the regular expression can be greatly simplified, consider (assuming the input is the peculiar US m/d/y format):

/* Validate a date string in US m/d/y format
** @param {string} s - string to parse
**                     separator can be any non–digit character (.-/ are common)
**                     leading zeros on values are optional
** @returns {boolean} true if string is a valid date, false otherwise
*/
function validateMDY(s) {
  var b = s.split(/\D/);
  var d = new Date(b[2],--b[0],b[1]);
  return b[0] == d.getMonth();
}

var testData = ['2/29/2016',   // Valid - leap year
                '2/29/2015',   // Invalid - day out of range
                '13/4/2016',   // Invalid - month out of range
                '13/40/2016',  // Invalid - month and day out of range
                '02/02/2017']; // Valid

document.write(testData.map(function(a) {
  return a + ': ' + validateMDY(a);
}).join('<br>'));
RobG
  • 142,382
  • 31
  • 172
  • 209