0

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>
</div>

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

Jonathan Anctil
  • 1,025
  • 3
  • 20
  • 44

2 Answers2

1

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: https://jsfiddle.net/5wa5478c/

Nikos Paraskevopoulos
  • 39,514
  • 12
  • 85
  • 90
  • I have a question, maybe you can respond. This ng-pattern need to be dynamic and set by the controller depending the context. If I try to bind this regex, it don't work. If I remove the slash, it works... – Jonathan Anctil Jul 26 '16 at 20:26
  • 1
    You can do it as: ``, where `pattern` is placed in the scope by the controller. See https://jsfiddle.net/xsvpmp6c/ – Nikos Paraskevopoulos Jul 27 '16 at 11:11
0

With this, this regex indicates that valid input is the start of a line (^), followed by one of the approved characters, followed by the end of the line ($).

Remove ^ and $, and it should work!

ng-pattern='/[a-zA-Z_-]/'

Test your code here first: http://rubular.com/

Tori Huang
  • 527
  • 1
  • 7
  • 25
  • Yeah I've tested it on another RegEx website online, but in my Angular code it raise a pattern error regardless the second character I enter (valid or not!) – Jonathan Anctil Jul 26 '16 at 18:55
  • Remove ^ and $ as stated above, and it should work. Your code as is does not work on rubular, but works with this fix. – Tori Huang Jul 26 '16 at 18:55
  • I've removed those characters and it allow now everything (It works only for the first character) – Jonathan Anctil Jul 26 '16 at 19:05