Does ng-pattern give "Lexer Error"?

As an attribute of the input element, I have:

ng-pattern="^\d{5}(?:[-\s]\d{4})?$" 

Is this expression wrong?

I get this error:

 Lexer Error: Unexpected next character at columns 0-0 [^] in expression [^\d{5}(?:[-\s]\d{4})?$]. 
+8
javascript angularjs regex
source share
4 answers

Try adding / before ^ and after the $ sign.

eg.

 ng-pattern="/^\d{5}(?:[-\s]\d{4})?$/" 

Hope this helps!

+28
source share

By default, angularjs wraps the regular expression with ^ and $ . Remove them.

Code snippet:

 var f, g = d.ngPattern || d.pattern; d.$observe("pattern", function(a) { C(a) && 0 < a.length && (a = new RegExp("^" + a + "$")); 
+5
source share

If you want to put your regular expression in code, not in html:

In the controller:

 function SomeController() { var vm = this; vm.regex = /^\d{5}(?:[-\s]\d{4})?$/.source; } 

In html (assuming your controller has an alias like "ctrl"):

 ng-pattern="ctrl.regex" 
+2
source share

If someone encounters a problem like this: Lexer error: Unexpected next character in columns 7-7 [#] in the expression [consts. # Contact]

Through:

Controller:

 app.controller('XXController', function($rootScope, $scope, $q, XXService, configuration, constants) { $scope.consts = constants.constants; //... }); 

constants_en.json:

 { "#Contact":"Contact Details", ... } 

HTML:

 <label for="contact">{{ consts.#Contact }} </label> 

Solution: Use the following code in HTML:

 <label for="customer">{{ consts['#Contact'] }}</label> 
0
source share

All Articles