Reputation: 163
I'm trying to add an input restriction pattern in Angular 5 to an input field so users can only input the following (1234567890-.)
<div class="input-group">
<input type="text" id="btn" (keyup.enter)="Submit(Car.value);" class="form-control" name="Car" #Car required placeholder="Car name" [value]="CarSearch" [pattern]="nameFormat"> </div>
And in the component: i declare my pattern(wrong regex pattern):
nameFormat = "[a-zA-Z\s]+$";
then in constructor:
this.name = new FormControl("", Validators.compose([Validators.required, Validators.pattern(this.nameFormat)]));
How can i achieve the correct regex pattern and restrict user input, the current solution is not working...thank you for suggestions and ideas.
Upvotes: 1
Views: 11025
Reputation: 26
Instead of using regex pattern,you can achieve this by using keycodes.
In component.html
<input class="form-control" (keypress)="omit_number($event)" type="text">
In component.ts
omit_number(event) {
var key;
key = event.charCode; // key = event.keyCode; (Both can be used)
return ((key > 47 && key < 58) || key == 45 || key == 46);
}
Explanation
(key > 47 && key < 58) // allows numbers from 1 to 0
key == 45 // allows minus(-)
key == 46 //allows Period(.)
Upvotes: 1