I'm trying to check whether a date is valid using the following function which I found online (which I changed to my date format):
function isValidDate(date)
{
var matches = /(\d{4})[-\/](\d{2})[-\/](\d{2})/.exec(date);
if (matches == null) return false;
var day = matches[2];
var month = matches[1] - 1;
var year = matches[3];
var posedDate = new Date(year, month, day);
return posedDate.getDate() == day &&
posedDate.getMonth() == month &&
posedDate.getFullYear() == year;
}
It was for the format MM/DD/YYYY but i tried changing the regex so there was {4} for the first part (which was {2}) and the last one to {2} which was {4}. Sorry, I don't really know what I'm doing with regex within JavaScript.
Thanks for any help!
I'm trying to check whether a date is valid using the following function which I found online (which I changed to my date format):
function isValidDate(date)
{
var matches = /(\d{4})[-\/](\d{2})[-\/](\d{2})/.exec(date);
if (matches == null) return false;
var day = matches[2];
var month = matches[1] - 1;
var year = matches[3];
var posedDate = new Date(year, month, day);
return posedDate.getDate() == day &&
posedDate.getMonth() == month &&
posedDate.getFullYear() == year;
}
It was for the format MM/DD/YYYY but i tried changing the regex so there was {4} for the first part (which was {2}) and the last one to {2} which was {4}. Sorry, I don't really know what I'm doing with regex within JavaScript.
Thanks for any help!
Share Improve this question asked Mar 7, 2014 at 23:37 HaychHaych 9422 gold badges18 silver badges41 bronze badges 4- 2 webdeveloper./forum/… – Robert Harvey Commented Mar 7, 2014 at 23:38
-
The number in braces (e.g.
{2}
) represents the number of times the preceding symbol (e.g.\d
) is to be repeated. Does this answer your question? – Xynariz Commented Mar 7, 2014 at 23:40 -
2
I think you also need to change around the order of
var day = matches[2]; var month = matches[1] - 1; var year = matches[3];
so that it aligns with your changed-around format. – Robert Harvey Commented Mar 7, 2014 at 23:40 - @RobertHarvey I found this codecademy course more helpful to learn codecademy./courses/javascript-intermediate-en-NJ7Lr/0/1 – jonperl Commented May 1, 2014 at 15:19
1 Answer
Reset to default 4You should also change the order of reading the data:
var year = matches[1];
var month = matches[2] - 1;
var day = matches[3];
So in case your format is YYYY/MM/DD, the first matched group should be the year, the second the month, and the third the day. This way the function should work.
- jsFiddle Demo
- Learn Regex, it is fun! Not as difficult as it seems and is worth it.