2

How can I remove special characters while I'm typing in the input field. I used (keyup) or (keydown) and replace for this. I attached the code. I will appreciate any help. Thanks!

removeSpecialCharacters(event) { let newVal = event.target.value.replace('[^A-Za-z0-9]', ''); return newVal; }
<input maxlength="10" (keydown)="this.removeSpecialCharacters($event)">

3 Answers 3

5

You can use this Directive

import { Directive, HostListener, ElementRef, Input } from '@angular/core'; @Directive({ selector: '[specialIsAlphaNumeric]' }) export class SpecialCharacterDirective { regexStr = '^[a-zA-Z0-9_]*$'; @Input() isAlphaNumeric: boolean; constructor(private el: ElementRef) { } @HostListener('keypress', ['$event']) onKeyPress(event) { return new RegExp(this.regexStr).test(event.key); } @HostListener('paste', ['$event']) blockPaste(event: KeyboardEvent) { this.validateFields(event); } validateFields(event) { setTimeout(() => { this.el.nativeElement.value = this.el.nativeElement.value.replace(/[^A-Za-z ]/g, '').replace(/\s/g, ''); event.preventDefault(); }, 100) } } 

like <input specialIsAlphaNumeric placeholder="my love" value="Mam"> don't forget add the Directive class in declarations on ngModule

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

4 Comments

How can i use another directive for currency xx.xxx,xx? i opened another questions for this? Can you please help me?
Do you need it while typing?
Yes, while typing.
2

Now newVal isn't in any way connected to your input element. Try binding it using, for example, ngModel:

inputModel: string; removeSpecialCharacters(event) { this.inputModel = event.target.value.replace('[^A-Za-z0-9]', ''); } 
<input maxlength="10" (keydown)="this.removeSpecialCharacters($event)" [(ngModel)]="inputModel"> 

Comments

1

use data binding and (change) event listener. if you're going for a form then consider using formbuilder and using formControlName for data bindig. that's an easier approach.

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.