2

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

1

2 Answers 2

6

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 });
});
Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.