Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
733 views
in Technique[技术] by (71.8m points)

angular - Proper way to restrict text input values (e.g. only numbers)

Is it possible to implement an input that allows to type only numbers inside without manual handling of event.target.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.

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.

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

But in both implementation there is essential problem:

  1. when you type 10 (model value is 10; input value is 10) - correct
  2. when you type 10d afterwards (model value is 10 - not modified, all non-digits has been removed; input value is 10d) - incorrect, because the model value is the same as before
  3. when you type 10d3 - (model value is 103; input value is 103) - correct

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

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();
    }
}

In your template use the following

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

This will catch the input before angular2 catches the event.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...