-1

I have an input field. I want to restrict user from entering special characters. Only alphanumeric values are allowed. I have implemented below code but when any special characters is pressed it is visible in input field.

component.html

 <input type="text" placeholder="Name" [formControl]="myName" (ngModelChange)="value($event)">

component.ts

value(text: any){
text = text.replace(/[^a-zA-Z0-9-]/g, '');
}
neelam
  • 119
  • 1
  • 5
  • 14
  • You can't restrict a user from inserting invalid data/characters into an input. That's why you should always validate the input and throw an error message to the user when an invalid input is recognized. – tacoshy Apr 05 '23 at 13:56

2 Answers2

0

You can take a look at Best way to alphanumeric check in JavaScript and check your string with it.

Using the anwser's code, you can even code a thing like this :

text = text.split('').filter(c => isAlphaNumeric(c)).join('');

Or you can use the pattern HTML attribute, it will be cleaner -> pattern="[a-zA-Z0-9 ]+"

Bibimission
  • 317
  • 5
  • 17
-1

You probably need to assign the modified value back to the control in the event handler.

value(text: any) {
    text = text.replace(/[^a-zA-Z0-9-]/g, '');
    this.form.get('myName').setValue(text);
}
Martin Staufcik
  • 8,295
  • 4
  • 44
  • 63