簡體   English   中英

如何限制一個字段只接受 4 個數字字符作為輸入?

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

我想要一個文本字段只接受數字,因為一些控制鍵和數字應該正好是四位數長,不少於不少。 我的驗證碼是

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 頁面中像這樣調用這個驗證 function

<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/

編輯:就我個人而言,我喜歡Masked Input jQuery 插件,但如果這就是你需要做的所有事情,這可能是一個笨拙的解決方案。

很多很多jQuery 插件已經以一種或另一種形式做到了這一點。

一個主要做你想要的1的是Masked Input Plugin 如果可以的話,我建議使用現有的、有效的和經過驗證的東西,而不是重新發明。

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>
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 輸入 maxlength屬性,並在相同的輸入尺寸屬性中設置固定寬度 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], '')
        }
    }
});

這是一個簡單的方法。 在事件更改文本之前存儲舊文本。 然后檢查新文本是否有效。 如果不是,則恢復為舊文本。 要進一步確保最多 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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM