首页 > 解决方案 > 如何允许除数字以外的所有字符?

问题描述

我想允许除数字之外的所有字符。我在jquery下面写了。

$(".no-numbers").keypress(function(e){
  if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) 
  {
    swal({
    title: "",
    text: "Numbers are not allowed"
    });

    return false;
  }
  else
  {
    return true;
  }
}); 

上面的代码不接受任何东西......请帮忙!!!

标签: javascriptjquery

解决方案


尝试以下操作:

$(".no-numbers").keypress(function(e){
  var key = e.keyCode;
  if (key >= 48 && key <= 57) {
    swal({
    title: "",
    text: "Numbers are not allowed"
    });

    return false;
  }
  else
  {
    return true;
  }
}); 

或者您可以使用正则表达式,例如:

var regex = new RegExp("^[a-zA-Z\s]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
  // do your stuff here
}

推荐阅读