Jonathan Anctil Jonathan Anctil - 5 months ago 27
AngularJS Question

How to use ngPattern to validate an input containing restricted characters?

I try to validate the input of restricted characters. The input field only accept alphabet, dash and underscore characters.

When I test the code below, the first character is accepted, but the second one raise a pattern error.

My RegEx: /^[a-zA-Z_-]$/

HTML code:

<input ng-model="inputText" name="inputText" required md-maxlength="{{options.maxTextLength}}" md-autofocus ng-keypress="keypress($event)" ng-change="textChanged()" ng-pattern='/^[a-zA-Z_-]$/'>
<div ng-messages="inputTextForm.inputText.$error">
<div ng-message="required">Input is required.</div>
<div ng-message="md-maxlength">Input has reached the maximum characters allowed.</div>
<div ng-message="pattern">Invalid characters.</div>

This code is in an Angular Material Dialog (v1.0.9)


For more than one character you need the * at the end of the pattern, i.e.:

<input ... ng-pattern="/^[a-zA-Z_-]*$/" />
<!--                               ^   -->
<!--                               |   -->
<!--             HERE -------------+   -->

See fiddle: