murday1983
murday1983

Reputation: 4006

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

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:

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

Upvotes: 9

Views: 80395

Answers (5)

Kamil Kiełczewski
Kamil Kiełczewski

Reputation: 92347

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" ... >

Upvotes: -2

Ghazni
Ghazni

Reputation: 836

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

firstName: [
        '',
        [
          Validators.required,
          Validators.maxLength(50),
          Validators.pattern('^[a-zA-Z ]*$')
        ]
      ],

Upvotes: 18

murday1983
murday1983

Reputation: 4006

My fix was to do it in my component

firstName: ['', Validators.pattern('^[a-zA-Z \-\']+')],

Upvotes: 7

Sudhakar M
Sudhakar M

Reputation: 9

Use this :

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

Upvotes: -5

Jayakrishnan
Jayakrishnan

Reputation: 4294

You need to use following to make pattern work

<input mdInput [(ngModel)]="details.firstName" placeholder="First name(s)" [pattern]="'^[a-zA-Z \-\']$'">

Upvotes: 2

Related Questions