有一个快速的方法来设置HTML文本输入(<input type=text />),只允许数字击键(加上'.')?


当前回答

使用这个正则表达式/\D*/g

const phoneHandler = (event: React.ChangeEvent<HTMLInputElement>) =>{
setPhone(event.target.value.replaceAll(/\D*/g, ''));};

其他回答

上面的一些答案使用了过时的内容,比如which的使用。

要检查按下的键是否为数字,可以使用keyup eventListener来读取event.key的值。如果不是数字,就不要输入字符。您可以将其他密钥加入白名单。例如,允许用户使用箭头在输入字段中向后或向前导航,或者按退格键并删除输入的数字。

validate (event) {
  const isNumber = isFinite(event.key)
  const whitelist = ['Backspace','Delete','ArrowDown','ArrowUp','ArrowRight','ArrowLeft']
  const whitelistKey = whitelist.includes(event.key)

  if (!isNumber && !whitelistKey) {
    event.preventDefault()
  }
}

这是我的一句话解决方案!

$('#input-field').keypress(e => !String.fromCharCode(e.which).match(/\D/g));

我个人建议使用http://www.decorplanit.com/plugin/的autonnumeric插件-它支持所有不同的变体,如前缀/后缀处理,货币处理,负值格式,最小值,最大值等。

如果你正在尝试有棱角的,这可能会有帮助

获取输入的数字(带小数点),然后

<input [(ngModel)]="data" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');">

现在这将不能正确地更新模型中的值 为了显式地改变model的值,添加这个

<input [(ngModel)]="data" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');" (change)="data = $event.target.value">

更改事件将在模型中的值更新后触发,因此它也可以用于响应式表单。

现在大多数浏览器都支持type="number"这个属性

<input type="number" maxlength="3" ng-bind="first">