验证JavaScript中出生日期
我想要出生日期的验证。我已经使用了新的日期方法,因此我不应该在今天之后获得日期。但是,即使我在今天之后插入日期也没有显示无效的日期。
var pattern = /^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$/
var date= new Date();
if (dateofbirth == "" || dateofbirth == null||!pattern.test(dateofbirth)) {
alert("invalid date of birth should in yyyy-mm-dd");
return false;
}
else if(dateofbirth >date){
alert("invalid date");
return false;
}
else{
alert("valid date");
}
I want the validation for date of birth. I have used new Date method so that i should not get date after today. But even though i insert date after today it doesn't show invalid date.
var pattern = /^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$/
var date= new Date();
if (dateofbirth == "" || dateofbirth == null||!pattern.test(dateofbirth)) {
alert("invalid date of birth should in yyyy-mm-dd");
return false;
}
else if(dateofbirth >date){
alert("invalid date");
return false;
}
else{
alert("valid date");
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
您可以我的代码:
You can you my code :
除第二条件外,您当前的代码很好。这应该是时间戳比较。
Your current code is good except for the second condition. It should be a timestamp comparison.
dateofbirth
未定义。尝试添加输入。
dateofbirth
is not defined. Try to add an input.
主要问题是
dateofbirth
变量是String
的一种类型。您应始终比较两种类似的变量类型,以确保结果一致。
注意事项
The primary issue is that the
dateofbirth
variable is a type ofstring
.You should always compare two similar variable types to ensure the results are consistent.
Considerations
在比较之前,请使用
sethours
函数将小时,分钟,秒和毫秒设置为零Use the
setHours
function to set the hours, minutes, seconds and milliseconds to zero before comparison您的dateofth变量是类型字符串的,而今天的日期是一个日期对象,因此当您比较dateofbirth是否大于当前日期。它将始终导致错误。为了解决此问题,您可以将日期构造函数传递给dateofth,该构造函数将其转换为日期对象,然后您可以将其转换为comapre。像这样:
Your dateofbirth variable is of type string whereas your today's date is a date object so when you are comparing whether dateofbirth is greater than current today's date or not. It will always result in false. To fix this you can pass your dateofbirth in Date constructor which will convert it into date object then you can comapre it. Like this:
如果要将DOB与当前日期进行比较,则需要首先将其变成日期对象:
正如最后两个测试用例所示,这也不是“完美”:JavaScript接受类似“ 1974-02-31”之类的输入,并将其解释为“ 1974年2月28日之后的3天”,即当年3月3日。
If you want to compare the DOB with the current date you need to turn it into a date object first:
As the last two test cases show, this is not yet "perfect" either: JavaScript accepts input like "1974-02-31" and will interpret it as "3 days after 28 February 1974", which is 3 March of that year.
由于
dateofbirth
是字符串,date
是对象,因此需要将它们转换为同一数据类型。最简单的类型比较(除布尔)是数字。我们可以date.parse()
每个都作为时间戳:Since
dateOfBirth
is a string anddate
is an object, they need to be converted to the same data type. Easiest type to compare (besides boolean) are numbers. We couldDate.parse()
each one as a timestamp: