Created
January 14, 2014 16:55
-
-
Save quagliato/8421619 to your computer and use it in GitHub Desktop.
Date validation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function validateDate(date, fieldName, afterToday){ | |
if(date.length < 10){ | |
alert(fieldName + ': tamanho inválido.'); | |
return false; | |
} | |
if(date.charAt(2) != '/' || date.charAt(5) != '/'){ | |
alert(fieldName + ': formatação inválida.'); | |
return false; | |
} | |
var year = parseInt(date.substr(6, 4)); | |
var month = parseInt(date.substr(3, 2)); | |
var day = parseInt(date.substr(0, 2)); | |
if(!year){ | |
alert(fieldName + ': ano inválido - ' + date.substr(6, 4)); | |
return false; | |
} | |
if(!month || month < 1 || month > 12){ | |
alert(fieldName + ': mês inválido - ' + date.substr(3, 2)); | |
return false; | |
} | |
if(!day || day < 1 || day > 31){ | |
alert(fieldName + ': dia inválido - ' + date.substr(0, 2)); | |
return false; | |
} | |
var major = new Array(1, 3, 5, 7, 8, 10, 12); | |
var minor = new Array(4, 6, 9, 11); | |
if(major.indexOf(month) != -1 && day > 31){ | |
alert(fieldName + ': para meses com 31 dias, o maior dia possível é 31.'); | |
return false; | |
}else if(minor.indexOf(month) != -1 && day > 30){ | |
alert(fieldName + ': para meses com 30 dias, o maior dia possível é 30.'); | |
return false; | |
}else if(month == 2){ | |
var leapyear = false; | |
if((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0){ | |
leapyear = true; | |
} | |
if(leapyear && day > 29){ | |
alert(fieldName + ': para meses com até 29 dias, o maior dia possível é 29.'); | |
return false; | |
}else if(!leapyear && day > 28){ | |
alert(fieldName + ': para meses com até 28 dias, o maior dia possível é 28.'); | |
return false; | |
} | |
} | |
date = new Date( | |
year, | |
month - 1, | |
day, | |
0, | |
0, | |
0 | |
); | |
var now = new Date(); | |
if (afterToday) { | |
if(date < now){ | |
alert(fieldName + ' não pode ser anterior a hoje.'); | |
return false; | |
} | |
} | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment