限制文本输入值(例如仅数字)的正确方法 [英] Proper way to restrict text input values (e.g. only numbers)

查看:116
本文介绍了限制文本输入值(例如仅数字)的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以实现一个input,该类型允许仅在内部键入数字而无需手动处理event.target.value?

Is it possible to implement an input that allows to type only numbers inside without manual handling of event.target.value?

在React中,可以定义value属性,然后将输入更改基本绑定到该值(如果不更改value,则无法修改它).请参见示例.无需任何努力,它就可以正常工作.

In React, it is possible to define value property and afterwards input change will be basically bound to the value (not possible to modify it without value change). See example. And it works just fine without any efforts.

在Angular 2中可以定义[value],但是它只会在开始时设置该值,然后不会阻止input进行修改.

In Angular 2 it is possible to define [value], but it will just set the value initially, and afterwards input is not prevented from the modifications.

我正在玩ngModel[value] / (input),请参见示例.

I was playing around with ngModel and [value] / (input), see example.

但是在这两种实现方式中,都存在一个基本问题:

But in both implementation there is essential problem:

  1. 键入10(模型值为10;输入值为10)时-正确
  2. 之后输入10d(模型值是10-未修改,所有非数字已删除;输入值是10d)-错误,因为模型值与之前相同
  3. 键入10d3时-(模型值为103;输入值为103)-正确

如何(从第一眼看)如何做这种简单的组件,而无需手动处理event.target.value?...

How to do that simple (from the first glance) component, without manually handling event.target.value?...

更新,我不是在这里寻找本机HTML5 input[number]元素.这里输入的数字仅作为示例-当我需要限制输入文本时,可能会有更多的任务.

UPDATE I am not looking for native HTML5 input[number] element here. Numbers input here is just for the example - there could be way more tasks when i need to restrict input text.

此外,input[number]是1)不限制我键入10ddd,并且2)(重要性较低)包含我不需要的箭头.

Moreover, input[number] is 1) not restricting me from typing 10ddd and 2) (less important) contains arrows that i do not need.

这里的问题是防止输入超出限制值的内容,而不是允许输入任何并随后进行验证

And the problem here is to prevent user from typing something beyond the restricted values, instead of allow to input anything and validate it afterwards

推荐答案

在component.ts中添加此功能

In component.ts add this function

_keyUp(event: any) {
    const pattern = /[0-9\+\-\ ]/;
    let inputChar = String.fromCharCode(event.key);

    if (!pattern.test(inputChar)) {
      // invalid character, prevent input
      event.preventDefault();
    }
}

在模板中使用以下内容

<input(keyup)="_keyUp($event)">

这将在angular2捕获事件之前捕获输入.

This will catch the input before angular2 catches the event.

这篇关于限制文本输入值(例如仅数字)的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆