javascript - 输入 : Disable letters only

标签 javascript jquery

如何禁用输入中的字母,但仍允许用户键入 +( ) 等符号,并添加空格

jsFiddle

$(".phone").on("keypress keyup blur",function (e) {    
    $(this).val($(this).val().replace(/^[a-zA-Z]+$/, ""));
        if ((e.which < 48 || e.which > 57)) {
            e.preventDefault();
    }
});

最佳答案

$(".phone").on("keypress keyup blur", function (event) {
  switch (event.keyCode) {
    case 43: // + character
    case 40: // the ( character
    case 41: // the ) character
      break;
    default:
      const regex = new RegExp("^[a-zA-Z0-9.,/ $@()]+$");
      const key = event.key;
      if (!regex.test(key)) {
        event.preventDefault();
        return false;
      }
      break;
  }
});

关于javascript - 输入 : Disable letters only,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31968008/

相关文章:

javascript - componentDidMount 上的几个请求

JavaScript 在 2 张图片后淡入太快

javascript - 如何在javascript中按当前月份过滤对象数组

javascript - 如何中止淡出 jqueryui 菜单?

jquery - 在页面加载时保持 Kendo Treeview 的扩展状态

javascript - 全局记录 jQuery 错误(事件和 DOM 错误)

javascript - 如何立即加载深色主题

jquery - 如何在 jQuery 中为 getJSON 设置缓存 false?

jquery - HTML 选项卡 CSS 在 firefox 和 chrome 中工作,但在 internet explorer 中不工作

javascript - 带有双引号的数据属性的 jQuery JSON 解析失败