Reputation: 35
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
Upvotes: 2
Views: 4301
Reputation: 11
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>
Upvotes: 1
Reputation: 1780
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 });
});
Upvotes: 6