Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

angular

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

like image 401
ValeriiVasin Avatar asked May 25 '16 11:05

ValeriiVasin


People also ask

How do I restrict input fields with only numbers?

To limit an HTML input box to accept numeric input, use the <input type="number">. With this, you will get a numeric input field.

How do I allow only the letters in the input field?

To get a string contains only letters (both uppercase or lowercase) we use a regular expression (/^[A-Za-z]+$/) which allows only letters. Next the match() method of string object is used to match the said regular expression against the input value. Here is the complete web document.


1 Answers

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.

like image 159
weizong song Avatar answered Oct 07 '22 00:10

weizong song