I want to validate a mobile number using Angular 4 and it should not accept any characters other than numbers up to just 10 digits.
Below is my code ,
<input type="text" formControlName="mobileNo" minlength=10 maxlength=10>
just add validators pattern
mobileNumber: new FormControl(null, [Validators.pattern("[0-9]{0-10}")])
and the type will be number and it will avoid accepting any character
<input type="text" (keypress)="keyPress($event)" minlength=10 maxlength=10>
keyPress(event: any) {
const pattern = /[0-9\+\-\ ]/;
let inputChar = String.fromCharCode(event.charCode);
if (event.keyCode != 8 && !pattern.test(inputChar)) {
event.preventDefault();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With