skip to Main Content

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


  1. 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 ]+"

    Login or Signup to reply.
  2. 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);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search