1
I have tested several expressions, but I did not get the desired result.
How can I validate the date for yyyy/mm/dd
?
1
I have tested several expressions, but I did not get the desired result.
How can I validate the date for yyyy/mm/dd
?
2
Example in JSFIDDLE. This way you can validate the date in the formats: yyyy-mm-dd , yyyy/mm/dd , yyyy.mm.dd
function data_valida(date)
{
var matches = /(\d{4})[-.\/](\d{2})[-.\/](\d{2})/.exec(date);
if (matches == null) {
return false;
}
var dia = matches[3];
var mes = matches[2] - 1;
var ano = matches[1];
var data = new Date(ano, mes, dia);
return data.getDate() == dia && data.getMonth() == mes && data.getFullYear() == ano;
}
alert(data_valida('2016.05.26'));
Thank you for the reply
You’re welcome. I’m glad you could help
I’m racking my brain here to understand how this "Matches" works, because I need to validate a date in this format: YYYY-MM-DD HH:mm:ss
. I know this post is already kind of old, but if anyone can guide me I appreciate.
-1
Javascript function to validate mask and date value in Brazilian format.
if(validateDate("27/04/2009"))
console.log("OK");
else
console.log("Data incorreta");
function validateDate(data) {
// Ex: 10/01/1985
var regex = "\\d{2}/\\d{2}/\\d{4}";
var dtArray = data.split("/");
if (dtArray == null)
return false;
// Checks for dd/mm/yyyy format.
var dtDay= dtArray[0];
var dtMonth = dtArray[1];
var dtYear = dtArray[2];
if (dtMonth < 1 || dtMonth > 12)
return false;
else if (dtDay < 1 || dtDay> 31)
return false;
else if ((dtMonth==4 || dtMonth==6 || dtMonth==9 || dtMonth==11) && dtDay ==31)
return false;
else if (dtMonth == 2)
{
var isleap = (dtYear % 4 == 0 && (dtYear % 100 != 0 || dtYear % 400 == 0));
if (dtDay> 29 || (dtDay ==29 && !isleap))
return false;
}
return true;
}
Browser other questions tagged javascript regex
You are not signed in. Login or sign up in order to post.
vc just want to validate whether the text is a valid date or just the format?
– rray
I need to check if in a text there is a date in this format
– Thiago R.
With fields to separate or can be with "-", or other?
– Sergio
It would be interesting to accept "-" or "/" as a separator. To check whether the date is valid, would it be interesting to use regex, or a function for that? for example, 0000/00/00 -> does not validate.
– Thiago R.
Just remembering that it is a not very usual way to validate date, only regex not confirm whether the date is valid or not, be careful with this.
– user46523
@João Você refers to the date in relation to the current time, or to the format or to the 2 ?
– MagicHat
@Magichat I speak on valid date even, regardless of time. The format itself you can even validate, but the date value being valid or not is better to use some library like http://momentjs.com/ for javascript is the best! The legal that it also confers formats ...
– user46523
@John ah looted...
– MagicHat