How to validate date with leap year in JavaScript?
How to validate date with leap year in JavaScript?
Another way is to check which month falls on February 29 (February 29 or March 1?). If it is February the year is leap:
function anoBissexto(ano) {
return new Date(ano, 1, 29).getMonth() == 1
}
Remembering that months range from 0 to 11 for the JavaScript Date object (month 1 is February).
Hello, try this here:
function leapYear(year){
return ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
}
Date validation with javascript, also checks if the year is leap year.
<html>
<head>
<title>valida data</title>
<script>
function valData(data){//dd/mm/aaaa
day = data.substring(0,2);
month = data.substring(3,5);
year = data.substring(6,10);
if( (month==01) || (month==03) || (month==05) || (month==07) || (month==08) || (month==10) || (month==12) ) {//mes com 31 dias
if( (day < 01) || (day > 31) ){
alert('invalid date');
}
} else
if( (month==04) || (month==06) || (month==09) || (month==11) ){//mes com 30 dias
if( (day < 01) || (day > 30) ){
alert('invalid date');
}
} else
if( (month==02) ){//February and leap year
if( (year % 4 == 0) && ( (year % 100 != 0) || (year % 400 == 0) ) ){
if( (day < 01) || (day > 29) ){
alert('invalid date');
}
} else {
if( (day < 01) || (day > 28) ){
alert('invalid date');
}
}
}
}
</script>
</head>
<body>
<form>
<input type="text" name="data" id="data" onBlur="return valData(this.value)" />
</form>
</body>
</html>
Here is a function I did. It's simple and works in a way:
function ValidarData() {
var aAr = typeof (arguments[0]) == "string" ? arguments[0].split("/") : arguments,
lDay = parseInt(aAr[0]), lMon = parseInt(aAr[1]), lYear = parseInt(aAr[2]),
BiY = (lYear % 4 == 0 && lYear % 100 != 0) || lYear % 400 == 0,
MT = [1, BiY ? -1 : -2, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1];
return lMon <= 12 && lMon > 0 && lDay <= MT[lMon - 1] + 30 && lDay > 0;
}
ValidarData(31,12,2016) // True
or
ValidarData("29/02/2017") // False