如何设置输入框输入值不是中文和空格

方法一:使用正则表达式验证输入值是否合法。

<input type="text" id="myInput">

<script>
  const input = document.getElementById("myInput");
  
  input.addEventListener("input", function() {
    const value = this.value;
    const regex = /^[一-龥\s]+$/; // 匹配中文和空格的正则表达式
    
    if (!regex.test(value)) {
      this.value = value.replace(/[^一-龥\s]+/g, ""); // 将非中文和空格的字符替换为空
    }
  });
</script>

方法二:使用input事件和ASCII码验证输入值是否合法。

var input = document.getElementById("myInput");
input.addEventListener("input", function() {
  var value = this.value;
  var newValue = '';
  for (var i = 0; i < value.length; i++) {
    var asciiCode = value.charCodeAt(i);
    if ((asciiCode >= 0 && asciiCode <= 64) || (asciiCode >= 91 && asciiCode <= 96) || (asciiCode >= 123 && asciiCode <= 127)) {
      continue; // 排除掉ASCII码表中不符合条件的字符
    } else {
      newValue += value.charAt(i);
    }
  }
  this.value = newValue;
});

上述代码中,我们使用for循环遍历输入的值中的每一个字符,并使用charCodeAt()方法获取每个字符的ASCII码。然后,我们根据ASCII码表中不符合要求的字符的范围来排除掉这些字符,只保留符合条件的字符。最后,我们使用一个新的字符串变量newValue来保存符合条件的字符,并将其赋值给输入框的value属性。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值