【问题标题】:How to restrict a field to take only 4 numeric characters as input?如何限制一个字段只接受 4 个数字字符作为输入?
【发布时间】:2011-07-22 13:21:13
【问题描述】:

我希望一个文本字段只包含数字和一些控制键,并且数字应该正好是四位数字,不少于不少。我的验证码是

function checkValidInput()
{
        $(".validateYearTextBox").keydown(function(event)
        {
            // Allow only delete, backspace,left arrow,right arraow and Tab
            if ( 
                   event.keyCode == 46 //delete
                || event.keyCode == 8  //backspace
                || event.keyCode == 37 //leftarow
                || event.keyCode == 39 //rightarrow
                || event.keyCode == 9  //tab
                )
                {
                // let it happen, don't do anything
                }
                else {
                    // Ensure that it is a number and stop the keypress
                    if ((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode <96 ||event.keyCode > 105) ) {
                        event.preventDefault(); 
                    }   
                }
        });

       $(".validateYearTextBox").keyup(function(event)
            {
                 var val = $(this).val();
                 if (val.length > 4){
                    alert ("Max length is 4");
                    val = val.substring(0, valore.length - 1);
                    $(this).val(val);
                    $(this).focus();
                    return false;
                  }
            });

}

在这里,我的第一个验证有效,但我的发送验证无效。

我在我的 aspx 页面中像这样调用这个验证函数

<script type="text/javascript">   
    $(document).ready(function(){
        checkValidInput(); 
    }
</script>

出了什么问题?

【问题讨论】:

  • “不工作”是什么意思?您必须包括真实的细节,否则回答者只是在猜测。在什么条件/输入下,当你 alert(val.length) 在你的 if 之前会发生什么,你期望发生什么,在你的 keydown 事件的每一行上实际发生什么等等等等?
  • @p.campbell:对不起,让我稍微修正一下我的代码,然后看看并提出建议,我会给出确切的细节,别担心。

标签: javascript jquery validation


【解决方案1】:

简化它:

function checkValidInput() {
    // Allow only delete, backspace, left arrow, right arrow, 
    // Tab, ctrl+v and numbers
    $(".validateYearTextBox").keydown(function(event) {
        if (!((event.keyCode == 46 || 
            event.keyCode == 8  || 
            event.keyCode == 37 || 
            event.keyCode == 39 || 
            event.keyCode == 9) || 
            (event.ctrlKey && event.keyCode == 86) ||  // Edit: Added to allow ctrl+v
            $(this).val().length < 4 &&
            ((event.keyCode >= 48 && event.keyCode <= 57) ||
            (event.keyCode >= 96 && event.keyCode <= 105)))) {
            // Stop the event
            event.preventDefault();
            return false;
        }
    });
    // Edit: Added validate after copy+paste.
    // This removes non-numeric characters and truncates the length
    // to 4 if the user copy + pasted.
    $(".validateYearTextBox").change(function(event) {
        var value =  $(this).val();
        value = value.replace(/[^0-9]/g,'');
        value = value.substr(0,4);
        $(this).val(value);
    });
}


$(document).ready(function() {
    checkValidInput();
});

http://jsfiddle.net/nwellcome/687kD/

编辑:我个人喜欢Masked Input jQuery 插件,但如果您只需要这样做,这可能是一个笨拙的解决方案。

【讨论】:

  • Gooooood 点,所以也许应该使用 $().change();让我解决这个问题。
  • 但我最初可以粘贴字母字符!请不要重新发明,请尝试使用现有插件(请参阅我的回答已在您的回答中推荐)。我怀疑插件的开销远远超过了花费在此上的时间。
  • 我同意你关于使用插件而不是重新发明验证的观点,将我的回复的那部分移到顶部是否合适?
【解决方案2】:

manymany jQuery 插件已经以一种或另一种形式做到了这一点。

主要1你想要的是Masked Input Plugin。如果可以的话,我建议使用现有的、有效的和经过验证的东西,而不是重新发明。

1 如果用户尝试输入超过n 个字符,它似乎没有做的唯一部分是显示错误,但我相信您可以修改插件或添加对&lt;input&gt;进行长度检查

【讨论】:

    【解决方案3】:

    使用正则表达式:

    enter code here
    function validator(elem,msg)
    {
    var exp=/^([0-9]+)$/; //it only allows for numbers
    if(elem.value.match(exp))
    {return true;}
    else
    {
      alert(msg);
      elem.focus();
      return false;
    }
    }
    

    html 代码:

    enter code here
    <html><head>
    <script src="javasript.js" type="text/javascript">
    </head>
    <body>
         <form method=POST>
         <input type='text' maxlength=4 name='num' id='num'>
         <input type='submit' value=OK onClick="validator(document.getElementById('num'),'Only four numbers and numbers only!');">
         </form> //the maxlength in input text tag restrict the maximum length of the input
         </body></html>
    

    【讨论】:

      【解决方案4】:

      这是一个简单的方法。在事件更改文本之前存储旧文本。然后检查新文本是否有效。如果不是,则恢复为旧文本。为了进一步确保最多 4 个字符,请为所有 &lt;input type="text"&gt; 元素添加一个 maxlength 属性。

      jQuery.fn.forceNumericOnly = function() {
          return this.each(function() {
              var oldText;
      
              $(this).keyup(function(e) {
                  var newText = $(this).val();
      
                  if (newText != "" && (isNaN(newText) || val.length > 4))
                      $(this).val(oldText);
                  else
                      oldText = $(this).val();
              })
      
              $(this).blur(function(e) {
                  var newText = $(this).val();
      
                  if (newText != "" && (isNaN(newText) || val.length > 4))
                      $(this).val(newText = oldText);
                  else
                      oldText = $(this).val();
              });
          })
      };
      
      $(".validateYearTextBox").forceNumericOnly();
      

      【讨论】:

        【解决方案5】:
        if (document.ExamEntry.examnum.value=="") {
        msg+="You must enter your examination number \n";
        document.ExamEntry.examnum.focus();
        document.getElementById('examnum').style.color="red";
        result = false;
        }
        

        【讨论】:

          【解决方案6】:
              $('.numeric').keypress(function(e) { 
          
                          var verified = (e.which == 8 || e.which == undefined || e.which == 0) ? null : String.fromCharCode(e.which).match(/[^0-9]/);
                          if (verified || e.delegateTarget.value.length>3 || e.ctrlKey ==true) { if(e.which!=8 ){e.preventDefault();}}
          
                }).on('paste',function(e){ e.preventDefault();});
          
          
          Here add class=numeric to input text box'. it will allow only 4 digits if you want to limit size to 2 digits change to e.delegateTarget.value.length>1 and so on as index starts from zero
          

          【讨论】:

          • 你能edit你的答案来解释为什么这回答了这个问题吗?
          • 有关您的答案的更多详细信息确实会有所帮助,因此请编辑和解释您的答案,否则恐怕会被删除。
          【解决方案7】:

          为此使用HTML input maxlength属性,并在同一input size属性中设置固定宽度4的大小值。

          <input type="text" maxlength="4" size="4">
          

          【讨论】:

            【解决方案8】:

            这是一个简单的答案,可以处理复制粘贴等所有问题。

            $(document).on("input", ".validateYearTextBox", function() {
                var value = this.value
                value = value.replace(/\D/g,'');
                for (i = 0; i < value.length; i++) {
                    if (i > 3) {
                        value = value.replace(value[i], '')
                    }
                }
            });
            

            【讨论】:

              猜你喜欢
              • 2014-06-06
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2015-03-31
              • 2020-12-02
              • 1970-01-01
              相关资源
              最近更新 更多