-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, ''); } 
1
  • 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. Commented Apr 5, 2023 at 13:56

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

-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); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.