For those who know how to code but need some quick javascript date parser for jump start, just copy paste it and take it for a spin. please comment if u've liked it or challenge me with a better solution. Note, there's a part of the code that I've copied from somewhere, and I can't remember where, if u find out where it's from tell me so I can give the credit to whom deserves it. One other thing, to test it I've used this:
<input id='dateID'
onblur='(this.value != "") ? dateValidation(this) : this.value = "";'
maxlength='10'/>
function dateValidation(date){
var year = "";
var min = 2003;
var max = 2100;
var month = "";
var day = "";
var daysInMonth = DaysArray(12);
var delimiter = "-";
var ymd = date.value;
var i;
for (i = 0; i < ymd.length; i++){
if( i < 4 ){
year = year + ymd.charAt(i);
} else if(i == 4 || i == 7){
if(ymd.charAt(i) != delimiter){
alertDateFormat(date);
break;
}
} else if( i >= 5 && i < 7 ) {
month = month + ymd.charAt(i);
} else if( i >= 8 && i < 10 ) {
day = day + ymd.charAt(i);
}
}
if(isValidYear(year, min, max) && isValidMonth(month)){
daysInMonth[2] = daysInFebruary(year);
if (day < 1 || day > daysInMonth[parseInt(month)]){
alertDateFormat(date);
} else {
}
} else {
alertDateFormat(date);
}
}
function daysInFebruary (year){
// February has 29 days in any year evenly divisible by four,
// EXCEPT for centurial years which are not also divisible by 400.
return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
for (var i = 1; i <= n; i++) {
this[i] = 31
if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
if (i==2) {this[i] = 29}
}
return this
}
function isValidMonth(month){
if(!isInteger(month)){
return false;
} else if(month < 1 || month > 12){
return false;
}
return true;
}
function isValidYear(year, min, max){
if(!isInteger(year)){
return false;
} else if (year < min || year > max){
return false;
}
return true;
}
function isInteger(s){
var i;
for (i = 0; i < s.length; i++){
// Check that current character is number.
var c = s.charAt(i);
if (((c < "0") || (c > "9"))) return false;
}
// All characters are numbers.
return true;
}
function alertDateFormat(date){
alert("Incorrect date, date format should be: yyyy-mm-dd");
date.value = "";
}
Sem comentários:
Enviar um comentário