JavaScript月份和日期和年份检查 [英] javascript month and day and year check
本文介绍了JavaScript月份和日期和年份检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试检查MM / DD / YYYY。
I am trying to check for MM /DD /YYYY.
当您输入0/0/0或00/00/0000时,我的脚本失败。我试图检查用户是否超过21岁,必须输入有效的两位数字,两位数字和数字年份。
currently my script fails when you enter 0 / 0 /0 or 00/00/0000. I am trying to check that the user is over 21 and must enter a valid two digit month, two digit day and 4 digit year.
任何建议?
$("#gate-box").submit(function() {
var day = $("#day").val();
var month = $("#month").val();
var year = $("#year").val();
var age = 21;
var mydate = new Date();
mydate.setFullYear(year, month - 1, day);
var currdate = new Date();
currdate.setFullYear(currdate.getFullYear() - age);
if ((currdate - mydate) < 0) {
$.msg("Sorry, you must be at least " + age + " to enter.");
return false;
}
else if (month > 12) {
$('#month').css({ 'border': '1px solid red' });
$.msg("Please enter a valid month.");
$('#month').focus();
return false;
}
else if (day > 31) {
$('#month').css({ 'border': 'none' });
$('#day').css({ 'border': '1px solid red' });
$.msg("Please enter a valid day.");
$('#day').focus();
return false;
}
else if (month.length === 0 || day.length === 0 || year.length === 0) {
$('#day').css({ 'border': 'none' });
$.msg("Please enter all fields.");
return false;
}
if ((currdate - mydate) > 0) {
$.colorbox.close()
$.setCookie('diageoagecheck', 'verified', { duration: 3 });
}
return false;
});
推荐答案
You should use the following method to validate if the input is indeed numeric, and then check the ranges
-isnumeric>使用JavaScript验证数字 - IsNumeric()
copied from Validate numbers in JavaScript - IsNumeric()
function IsNumeric(input)
{
return (input - 0) == input && input.length > 0;
}
使用这样(阅读输入后的 )
And use it like this (after reading the inputs)
if (!IsNumeric(day) || (day < 1) || (day > 31))
{/*handle wrong day here and return false*/}
if (!IsNumeric(month) || (month < 1) || (month > 12))
{/*handle wrong month here and return false*/}
if (!IsNumeric(year) || (year < 1900) || (year > 2100))
{/*handle wrong year here and return false*/}
这篇关于JavaScript月份和日期和年份检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文