如何限制一个字段只能输入4个数字字符?

我想要一个文本字段只取数字和一些控制键,数字应该是四位数长,而不是更少。 我的validation码是

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  57) && (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; } }); } 

在这里,我的第一次validation工作正常,但我的发送不起作用。

我在这样的aspx页面中调用了这个validation函数

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

出了什么问题?

简化它:

 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插件已经以这种或那种forms执行此操作。

一个大多数你想做的就是Masked Input Plugin 。 如果可以的话,我建议使用现有的,有效的和经过validation的,而不是重新发明。

1如果用户试图输入超过n字符,那么它似乎没有做的唯一部分就是显示错误但我确定你可以修改插件或在添加长度检查

使用正则表达式:

 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    
//the maxlength in input text tag restrict the maximum length of the input

这是一种简单的方法。 在事件更改文本之前存储旧文本。 然后检查新文本是否有效。 如果不是,则恢复为旧文本。 要进一步确保最多4个字符,请为所有元素添加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输入maxlength属性,并在相同的输入大小属性中设置固定宽度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], '') } } });