Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • 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

like image 345
murday1983 Avatar asked Jun 12 '17 07:06

murday1983


People also ask

How do I allow only the letters in the input field?

To get a string contains only letters (both uppercase or lowercase) we use a regular expression (/^[A-Za-z]+$/) which allows only letters. Next the match() method of string object is used to match the said regular expression against the input value. Here is the complete web document.

How to Allow Only Alphanumeric in textbox in Angular?

Allow Only Alphanumeric in Angular Input For handling the only alphanumeric in the input box we simply add an input control with the (keypress) event handler to call the keyPressAlphanumericl() .


2 Answers

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

firstName: [
        '',
        [
          Validators.required,
          Validators.maxLength(50),
          Validators.pattern('^[a-zA-Z ]*$')
        ]
      ],
like image 138
Ghazni Avatar answered Oct 22 '22 20:10

Ghazni


My fix was to do it in my component

firstName: ['', Validators.pattern('^[a-zA-Z \-\']+')],
like image 28
murday1983 Avatar answered Oct 22 '22 21:10

murday1983