我想做年度验证,它应该只是数字,它应该是4位数长,在1920年到当年之间我已经创建了java脚本函数,如下所示
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;
}
并在onkeypress="return yearValidation(this.value)"
但是当我输入1时,它会给我提醒Year should be in range 1920 to current year
答案 0 :(得分:5)
应用两个事件应该可以解决问题 HTML:
<input type="text"
onblur="yearValidation(this.value,event)"
onkeypress="yearValidation(this.value,event)"
>
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;
} }
}
答案 1 :(得分:0)
猜猜是:
if (year.length < 4) {
不是
if (year.length != 4) {
答案 2 :(得分:0)
或直接以表单
<input name="date_check"
type="text"
title="Date must be in this case:dd.mm.yy"
pattern="^[0-9]{1,2}\.[0-9]{2}$" />