0

I want to know how to only allow alphabet in an input, if a number or special character is entered in the input, ignore it, i work with Angular.

I work with reactive form but if I use pattern this just validates the field when submit is done, what I need is that for example if I press the number "1" in keyboard it simply does not show, when the key is pressed ignore everything that is not alphabet letter

Maiki
  • 15
  • 4
  • https://stackoverflow.com/questions/54460923/angular-2-restrict-input-field/54462816#54462816 – Eliseo Oct 19 '22 at 06:45

2 Answers2

3

You can use input mask libraries like this https://www.npmjs.com/package/ngx-mask. Or You can do it yourself like this

this.form.controls["Your Control Name Here"].valueChanges.subscribe((value: string) => {
    this.form.controls["Your Control Name Here"].setValue(value.replace(/[^A-Za-z]/, ""), { emitEvent: false });
});
zainhassan
  • 1,684
  • 6
  • 12
1

If what you want to achieve is a validation check, enforcing input is not a very user-friendly approach, as user type and is unable to figure out what is wrong. A better approach for validation should be a validation check and error with a proper explanation about what is wrong in typed input. (if your request is required for other reason, then feel free to ignore my comment)

for validation - you can use input pattern:
<input matInput type="text" [formControl]="your-control-name" pattern="[ a-zA-Z]*">

and as part of validation errors check you handle the pattern error: <mat-error *ngIf="formHandlersList[i].hasError('pattern')"> Only alphabetic characters are allowed

the full block of html looks something like this -

<mat-form-field appearance="standard" [style.width.px]="120">
   <input matInput type="text" [formControl]="your-control-name" pattern="[ a-zA-Z]*">
   <mat-error *ngIf="<your-form-control-object>.hasError('pattern')">
      Only alphabetic characters are allowed
   </mat-error>
</mat-form-field>
TsachiTw
  • 11
  • 3