Angular2 - Only Allow Alpha Characters TO Be Entered In An Input
Asked Answered
B

5

9

I am very new to Angular2 and cant seem to find my answer anywhere. I have an input (as show below) but I only want it to allow the following:

  • A-Z
  • a-z
  • '
  • -
  • [SPACE]

I have no idea on how to do this. I have tried ng-pattern="/^[a-zA-Z\s]*$/", pattern="/^[a-zA-Z\s]*$/" and ng-pattern-restrict="/^[a-zA-Z\s]*$/".

HTML

<td>
    <md-input-container>
        <input mdInput [(ngModel)]="details.firstName" placeholder="First name(s)" ng-pattern="/^[a-zA-Z\s]*$/">
    </md-input-container>
</td>

Ideally if a user enters a numeric character, I'd ether like it to be removed by itself or just not be allowed (not displayed) in the field

Bieber answered 12/6, 2017 at 7:37 Comment(0)
B
7

My fix was to do it in my component

firstName: ['', Validators.pattern('^[a-zA-Z \-\']+')],
Bieber answered 13/6, 2017 at 7:3 Comment(1)
Note that this only works for Reactive FromsCali
C
18

Angular Reactive Form Validation - To accept only alphabets and space.

firstName: [
        '',
        [
          Validators.required,
          Validators.maxLength(50),
          Validators.pattern('^[a-zA-Z ]*$')
        ]
      ],
Crumple answered 28/8, 2018 at 4:53 Comment(0)
B
7

My fix was to do it in my component

firstName: ['', Validators.pattern('^[a-zA-Z \-\']+')],
Bieber answered 13/6, 2017 at 7:3 Comment(1)
Note that this only works for Reactive FromsCali
I
2

You need to use following to make pattern work

<input mdInput [(ngModel)]="details.firstName" placeholder="First name(s)" [pattern]="'^[a-zA-Z \-\']$'">
Intuitive answered 12/6, 2017 at 7:42 Comment(2)
Thanks but this is causing the following error: Parser Error: Unexpected token ']' at column 14 in ['^[a-zA-Z \-']$'] in ng:///AppModule/PersonalDetailsComponent.html@12:91 ("tainer> <input mdInput [(ngModel)]="details.firstName" placeholder="First name(s)" [ERROR ->][pattern]="'^[a-zA-Z \-']$'"> </md-input-container> </td>Bieber
I have used the update but I am still able to enter 0-9 in the field.Bieber
T
-2

You can use following directive that allow to type strings which pass arbitrary regexp

import {Directive, HostListener, Input} from '@angular/core';

@Directive({selector: '[allowedRegExp]'})
export class AllowedRegExpDirective {
    
  @Input() allowedRegExp: string;
  
  @HostListener('keydown',['$event']) onKeyDown(event: any) {
    let k=event.target.value + event.key;

    if(['ArrowLeft','ArrowRight','ArrowUp','ArroDown','Backspace','Tab','Alt'
       'Shift','Control','Enter','Delete','Meta'].includes(event.key)) return;

    let re = new RegExp(this.allowedRegExp);
        
    if(!re.test(k)) event.preventDefault();
  }
}

example usage: 0-5 characters from your question

<input [allowedRegExp]="'^[a-zA-Z '-]{0,5}$'" type="text" ... >
Tantrum answered 26/3, 2020 at 13:31 Comment(0)
A
-5

Use this :

ng-pattern="/^[a-zA-Z]*$/"

Augustin answered 12/6, 2017 at 9:0 Comment(3)
Not sure why this is accepted answer - it is AngularJS way, not Angular which was required.Nevadanevai
Yes this is not an Angular2+ solutionLogomachy
here you can't enter a space. then it is invalidEbracteate

© 2022 - 2024 — McMap. All rights reserved.