1

我想进行年份验证,它应该只是数字,它应该是 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;
    }

并调用它onkeypress="return yearValidation(this.value)"

但是当我进入时1它会给我警报:

年份应该在 1920 年到当前年份的范围内

4

3 回答 3

6

应用两个事件应该可以解决问题。
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;
    } }
}
于 2013-01-09T07:05:11.513 回答
0

猜是:

 if (year.length < 4) {

不是

if (year.length != 4) {
于 2013-01-09T06:23:01.130 回答
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}$" />
于 2020-03-15T15:27:15.410 回答