Javascript 中的年份验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14229334/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Year validation in Javascript
提问by Edward
I want to do year validation whre it should be only numeric and Its should be 4 digit long and between 1920 to current year for that I have create Javascript function as follows:
我想做年份验证,它应该只是数字,它应该是 4 位长,并且在 1920 年到当前年份之间,为此我创建了 Javascript 函数,如下所示:
function yearValidation(year) {
var text = /^[0-9]+$/;
if (year != 0) {
if ((year != "") && (!text.test(year))) {
alert("Please Enter Numeric Values Only");
return false;
}
if (year.length != 4) {
alert("Year is not proper. Please check");
return false;
}
var current_year=new Date().getFullYear();
if((year < 1920) || (year > current_year))
{
alert("Year should be in range 1920 to current year");
return false;
}
return true;
}
and called it on onkeypress="return yearValidation(this.value)"
并调用它 onkeypress="return yearValidation(this.value)"
But when I enter 1it gives me alert:
但是当我进入时1它给了我警报:
Year should be in range 1920 to current year
年份应在 1920 年到当前年份的范围内
回答by vusan
Applying two event should solve the problem.
HTML:
应用两个事件应该可以解决问题。
HTML:
<input type="text"
onblur="yearValidation(this.value,event)"
onkeypress="yearValidation(this.value,event)"
>
JS:
JS:
function yearValidation(year,ev) {
var text = /^[0-9]+$/;
if(ev.type=="blur" || year.length==4 && ev.keyCode!=8 && ev.keyCode!=46) {
if (year != 0) {
if ((year != "") && (!text.test(year))) {
alert("Please Enter Numeric Values Only");
return false;
}
if (year.length != 4) {
alert("Year is not proper. Please check");
return false;
}
var current_year=new Date().getFullYear();
if((year < 1920) || (year > current_year))
{
alert("Year should be in range 1920 to current year");
return false;
}
return true;
} }
}
回答by Vimalnath
Guess it's:
猜猜是:
if (year.length < 4) {
not
不是
if (year.length != 4) {
回答by Mareg
Or directly in form
或者直接在表格中
<input name="date_check"
type="text"
title="Date must be in this case:dd.mm.yy"
pattern="^[0-9]{1,2}\.[0-9]{2}$" />

