I saw a potential answer here but that was for YYYY-MM-DD: JavaScript date validation
I modified the code code above for MM-DD-YYYY like so but I still can't get it to work:
String.prototype.isValidDate = function()
{
var IsoDateRe = new RegExp("^([0-9]{2})-([0-9]{2})-([0-9]{4})$");
var matches = IsoDateRe.exec(this);
if (!matches) return false;
var composedDate = new Date(matches[3], (matches[1] - 1), matches[2]);
return ((composedDate.getMonth() == (matches[1] - 1)) &&
(composedDate.getDate() == matches[2]) &&
(composedDate.getFullYear() == matches[3]));
}
How can I get the above code to work for MM-DD-YYYY and better yet MM/DD/YYYY?
Thanks.
Simple way to solve
DateFormat = DD.MM.YYYY or D.M.YYYY
I use this regex for validating MM-DD-YYYY:
It will match only valid months and you can use / - or . as separators.
I would use Moment.js for this task. It makes it very easy to parse dates and it also provides support to detect a an invalid date1 in the correct format. For instance, consider this example:
First
moment(.., formats)
is used to parse the input according to the localized format supplied. Then theisValid
function is called on the resulting moment object so that we can actually tell if it is a valid date.This can be used to trivially derive the isValidDate method:
1 As I can find scarce little commentary on the matter, I would only use moment.js for dates covered by the Gregorian calendar. There may be plugins for other (including historical or scientific) calendars.
This function will validate the date to see if it's correct or if it's in the proper format of: DD/MM/YYYY.
It works. (Tested with Firebug, hence the console.log().)