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, '');
}
2
Answers
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 :
Or you can use the pattern HTML attribute, it will be cleaner ->
pattern="[a-zA-Z0-9 ]+"
You probably need to assign the modified value back to the control in the event handler.