jquery – validation按键上的字符?

我有一个表单文本字段,我想只允许数字和字母。(即,没有#$!等等…)有没有办法抛出错误,并防止按键实际输出任何东西,如果用户尝试使用除数字和字母之外的任何字符? 我一直试图找到一个插件,但还没有找到任何能做到这一点的东西……

$('input').keyup(function() { var $th = $(this); $th.val( $th.val().replace(/[^a-zA-Z0-9]/g, function(str) { alert('You typed " ' + str + ' ".\n\nPlease use only letters and numbers.'); return ''; } ) ); }); 

编辑:

这里有一些其他好的答案可以防止输入发生。

我已经更新了我的,因为你也想显示错误。 替换可以使用函数而不是字符串。 该函数运行并返回替换值。 我添加了一个alert来显示错误。

http://jsfiddle.net/ntywf/2/

那么patrick的答案会删除字符,如果它是错误的,实际上是防止将字符插入到字段使用中

 $("#field").keypress(function(e) { // Check if the value of the input is valid if (!valid) e.preventDefault(); }); 

这样信就不会来到textarea

 $('#yourfield').keydown(function(e) { // Check e.keyCode and return false if you want to block the entered character. }); 

我发现在keypress和keyup上结合validation可以获得最佳结果。 如果要处理复制粘贴文本,则必须启用密钥。 如果跨浏览器问题允许非数字值进入文本框,这也是一个问题。

  $("#ZipCode").keypress(function (event) { var key = event.which || event.keyCode; //use event.which if it's truthy, and default to keyCode otherwise // Allow: backspace, delete, tab, and enter var controlKeys = [8, 9, 13]; //for mozilla these are arrow keys if ($.browser.mozilla) controlKeys = controlKeys.concat([37, 38, 39, 40]); // Ctrl+ anything or one of the conttrolKeys is valid var isControlKey = event.ctrlKey || controlKeys.join(",").match(new RegExp(key)); if (isControlKey) {return;} // stop current key press if it's not a number if (!(48 <= key && key <= 57)) { event.preventDefault(); return; } }); $('#ZipCode').keyup(function () { //to allow decimals,use/[^0-9\.]/g var regex = new RegExp(/[^0-9]/g); var containsNonNumeric = this.value.match(regex); if (containsNonNumeric) this.value = this.value.replace(regex, ''); }); 

你可以尝试这个扩展:

 jQuery.fn.ForceAlphaNumericOnly = function() { return this.each(function() { $(this).keydown(function(e) { var key = e.charCode || e.keyCode || 0; // allow backspace, tab, delete, arrows, letters, numbers and keypad numbers ONLY return ( key == 8 || key == 9 || key == 46 || (key >= 37 && key <= 40) || (key >= 48 && key <= 57) || (key >= 65 && key <= 90) || (key >= 96 && key <= 105)); }) }) }; 

用途:

 $("#yourInput").ForceAlphaNumericOnly(); 

上面的jquery扩展(ForceAlphaNumericOnly)很好,但仍允许通过以下字符!@#$%^&*()

在我的Mac上,当您按下shift键(键码16 )然后按1时 ,它会进入! 但键码为49 ,键码为1

 $(document).ready(function() { $('.ipFilter').keydown((e) => { if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 || (e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true) || e.keyCode === 67 && (e.ctrlKey === true || e.metaKey === true) || e.keyCode === 86 && (e.ctrlKey === true || e.metaKey === true) || e.keyCode === 82 && (e.ctrlKey === true || e.metaKey === true)) || (e.keyCode >= 35 && e.keyCode <= 40 )) { return; } if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) { e.preventDefault(); } }); });