0

I have a little problem with my regex in AngularJS

my regex in the html looks like this:

ng-pattern="[adfijmPrsyz\d]+"

but i get an error in the console which says:

angular.js:13920 Error: [$parse:lexerr] Lexer Error: Unexpected next character  at columns 12-12 [\] in expression [[adfijmPrsyz\d]+].

my regex should achieve this: Only a, d, f, i, j, m, P, r, s, y, z and numbers 0 to 9 should be valid.

it would be nice if i could set the regex in the controller instead of hardcoding it in the html file.

like this:

private regex: any = /[adfijmPrsyz\d+]/;

<input name="REFZEILE" ng-pattern="regex" />

Andrew
  • 235
  • 5
  • 11
  • 1
    Try using a regex literal notation in ng-pattern with `[0-9]` to see if there is any difference - `ng-pattern="/^[adfijmPrsyz0-9]+$/"`. See [this plunkr](https://plnkr.co/edit/6h9rSEcvEQEWvRoMY1cd?p=preview) for an example of how the regex can be set in the controller (`$scope.regex = '[adfijmPrsyz\\d]+';`). – Wiktor Stribiżew Dec 07 '16 at 14:30
  • 1
    `ngPattern` expects a scope variable, not a string. – a better oliver Dec 07 '16 at 15:36
  • @zeroflagL `ngPattern` accepts both, but when using a string you have to enclose it in quotes just like any other time you are supplying a string to an Angular directive. – Lex Dec 07 '16 at 15:42
  • @Lex Let's put it this way: It expects an expression. – a better oliver Dec 07 '16 at 15:53

1 Answers1

1

You can actually define the regex in your controller - you just need to use new RegExp(). When using regex inline you have to tell Angular that it's a string by enclosing it in quotes (single in your case since you are using double quotes on the attribute value), otherwise Angular tries to evaluate it as a variable. Here is a working example that shows both methods in action.

angular.module('app', ['ngMessages'])
  .controller('ctrl', function($scope) {
    $scope.regex = new RegExp(/^[adfijmPrsyz\d]+$/);
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-messages/1.5.9/angular-messages.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
  <form name="testForm">
    Using controller RegExp:
    <input type="text" name="testInput" ng-model="testInput" ng-pattern="regex" required>
    <div ng-messages="testForm.testInput.$error" role="alert">
      <div ng-message="required">A value is required</div>
      <div ng-message="pattern">Value entered is not valid</div>
    </div>
    Using inline RegExp:
    <input type="text" name="testInput2" ng-model="testInput2" ng-pattern="'[adfijmPrsyz\d]+'" required>
    <div ng-messages="testForm.testInput2.$error" role="alert">
      <div ng-message="required">A value is required</div>
      <div ng-message="pattern">Value entered is not valid</div>
    </div>
  </form>
</div>
Lex
  • 6,758
  • 2
  • 27
  • 42