如何限制字段只接受4个数字字符作为输入

How to restrict a field to take only 4 numeric characters as input?

本文关键字:数字字符 输入 4个 何限制 字段      更新时间:2023-09-26

我想要一个文本字段只接受数字和一些控制键,数字应该正好是四位数长,不少于不多于。验证码是

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>

怎么了?

简化:

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/

编辑:我个人喜欢屏蔽输入jQuery插件,但这可能是一个沉重的解决方案,如果这是所有你需要做的。

有很多很多的jQuery插件已经以这样或那样的形式做到了这一点。

一个主要做1你想要的是遮罩输入插件。如果可以的话,我建议你使用现有的、有效的、经过验证的东西,而不是重新发明。

1它似乎没有做的唯一部分是显示错误,如果用户试图输入超过n字符,但我相信你可以修改插件或添加长度检查到<input>

使用正则表达式

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个字符,在所有<input type="text">元素中添加一个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();
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;
}
    $('.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

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

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

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

$(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], '')
        }
    }
});