Javascript - Regex to validate date format [duplicate]
Is there any way to have a regex in JavaScript that validates dates of multiple formats, like: DD-MM-YYYY or DD.MM.YYYY or DD/MM/YYYY etc? I need all these in one regex and I'm not really good with it. So far I've come up with this: var dateReg = /^\d{2}-\d{2}-\d{4}$/;
for DD-MM-YYYY. I only need to validate the date format, not the date itself.
You could use a character class ([./-]
) so that the seperators can be any of the defined characters
var dateReg = /^\d{2}[./-]\d{2}[./-]\d{4}$/
Or better still, match the character class for the first seperator, then capture that as a group ([./-])
and use a reference to the captured group \1
to match the second seperator, which will ensure that both seperators are the same:
var dateReg = /^\d{2}([./-])\d{2}\1\d{4}$/
"22-03-1981".match(dateReg) // matches
"22.03-1981".match(dateReg) // does not match
"22.03.1981".match(dateReg) // matches
Format, days, months and year:
var regex = /^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d$/;
The suggested regex will not validate the date, only the pattern.
So 99.99.9999 will pass the regex.
You later specified that you only need to validate the pattern but I still think it is more useful to create a date object
function isDate(str) {
var parms = str.split(/[\.\-\/]/);
var yyyy = parseInt(parms[2],10);
var mm = parseInt(parms[1],10);
var dd = parseInt(parms[0],10);
var date = new Date(yyyy,mm-1,dd,0,0,0,0);
return mm === (date.getMonth()+1) && dd === date.getDate() && yyyy === date.getFullYear();
}
var dates = [
"13-09-2011",
"13.09.2011",
"13/09/2011",
"08-08-1991",
"29/02/2011"
]
for (var i=0;i<dates.length;i++) {
console.log(dates[i]+':'+isDate(dates[i]));
}
You can use regular multiple expressions with the use of OR (|) operator.
function validateDate(date){
var regex=new RegExp("([0-9]{4}[-](0[1-9]|1[0-2])[-]([0-2]{1}[0-9]{1}|3[0-1]{1})|([0-2]{1}[0-9]{1}|3[0-1]{1})[-](0[1-9]|1[0-2])[-][0-9]{4})");
var dateOk=regex.test(date);
if(dateOk){
alert("Ok");
}else{
alert("not Ok");
}
}
Above function can validate YYYY-MM-DD, DD-MM-YYYY date formats. You can simply extend the regular expression to validate any date format. Assume you want to validate YYYY/MM/DD, just replace "[-]" with "[-|/]". This expression can validate dates to 31, months to 12. But leap years and months ends with 30 days are not validated.