I need a regular expression for date format: dd-mm-yyyy in Javascript.
Notice
Your regexp does not work for years that "are multiples of 4 and 100, but not of 400". Years that pass that test are not leap years. For example: 1900, 2100, 2200, 2300, 2500, etc. In other words, it puts all years with the format \d\d00 in the same class of leap years, which is incorrect. – MuchToLearn
So it works properly only for [1901 - 2099] (Whew)
Well, I made this:
'31-12-1987'.match(/(3[01]|[2][0-9]|0\d)-(1[0-2]|0\[1-9])-\d{4}/)
Validates the day from 01 to 31, month from 01 to 12 and year of four digits. It only fails the february 30, and the months without 31 days. Which you can clean using the new Date('mm/dd/yyyy')
.
function parseDate(str) {
var m = str.match(/^(\d{1,2})-(\d{1,2})-(\d{4})$/);
return (m) ? new Date(m[3], m[2]-1, m[1]) : null;
}
Here is Regex for multiple date formats working for me :
//dd.MM.yyyy
var date_regex = /^(0[1-9]|1\d|2\d|3[01])\.(0[1-9]|1[0-2])\.(19|20)\d{2}$/;
alert(date_regex.test("02.02.1991"));
// //dd/mm/yyyy
// var date_regex = /^(0[1-9]|1\d|2\d|3[01])\/(0[1-9]|1[0-2])\/(19|20)\d{2}$/;
// alert(date_regex.test("02/12/1991"));
// //dd-mm-yyyy
// var date_regex = /^(0[1-9]|1\d|2\d|3[01])\-(0[1-9]|1[0-2])\-(19|20)\d{2}$/;
// alert(date_regex.test("02-12-1991"));
// //mm/dd/yyyy
// var date_regex = /^(0[1-9]|1[0-2])\/(0[1-9]|1\d|2\d|3[01])\/(19|20)\d{2}$/;
// alert(date_regex.test("12/02/1991"));
// //yyyy.MM.dd
// var date_regex = /^((19|20)\d{2})\.(0[1-9]|1[0-2])\.(0[1-9]|1\d|2\d|3[01])$/;
// alert(date_regex.test("1991.12.02"));
// //yyyy/MM/dd
// var date_regex = /^((19|20)\d{2})\/(0[1-9]|1[0-2])\/(0[1-9]|1\d|2\d|3[01])$/;
// alert(date_regex.test("1991/12/02"));
// //yyyy-MM-dd
// var date_regex = /^((19|20)\d{2})\-(0[1-9]|1[0-2])\-(0[1-9]|1\d|2\d|3[01])$/;
// alert(date_regex.test("1991-12-02"));
$('#DOB').blur(function () {
var s = $('#DOB').val(); alert('Entered date is:' + s);
var parms = s.split(/[\.\-\/]/);
var yyyy = parseInt(parms[2], 10);
var d = new Date();
var n = d.getFullYear(); //alert('current year is :' + n);
if (yyyy > n || yyyy < 1900) {
alert('Improper date format, Please enter dd/mm/yyyy format. (invalid year)');
}
var mm = parseInt(parms[1], 10);
if (mm > 12 || mm < 0)
{
alert('Improper date format, Please enter dd/mm/yyyy format. (invalid month');
}
var dd = parseInt(parms[0], 10);
if (dd > 31 || dd < 0)
{
alert('Improper date format, Please enter dd/mm/yyyy format. (invalid day');
}
//var date = new Date(dd, mm - 1, yyyy, 12, 0, 0, 0);
//var ndate = (date.getMonth() + 1) && ddmm === date.getDate() && yyyy === date.getFullYear();
// alert('new date is:' + ndate);
});
Try this:
'01-01-2012'.match( /\d{2}-\d{2}-\d{4}/ )
Note that that this way the date 33-12-2022 would be considered valid as well!