简体   繁体   中英

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

I wanted a text field to take only numbers ans some control keys and number should be exactly four digit long, not less not more. My validation code is

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;
                  }
            });

}

Here, my first validation is working, but my send one is not working.

I am calling this validation function in my aspx page like this

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

What is going wrong?

Simplify it:

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/

Edit: Personally I like the Masked Input jQuery plugin but that might be a heavy-handed solution if this is all you need to do.

There are many , many jQuery plugins that already do this in one form or another.

One that does mostly 1 what you want is Masked Input Plugin . If you can, I recommend using something existing, working and proven, rather than reinventing.

1 The only part that it doesn't seem to do is display an error if a user tries to enter more than n characters but I'm sure you could modify the plugin or add a length check to the <input>

Use regular expression:

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;
}
}

the html code:

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

Use HTML input maxlength attribute for this and also set the size value of fixing width 4 in same input size attribute.

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

Here is a simple answer that takes care of copy paste and all.

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

Here's a simple way of doing it. Stores the old text before an event changes the text. Then check to see if the new text is valid or not. If it isn't, then revert back to the old text. To further ensure the maximum of 4 characters, add a maxlength attribute to all <input type="text"> elements.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM