Search code examples
angularangular2-formsangular2-directives

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


Solution

  • My fix was to do it in my component

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