19

I'm terrible with regular expressions but I was wondering if it was possible to use ng-pattern with a variable

For example,

ng-pattern="/^{{validationCode}}$/"

where validationCode is a variable attached to $scope in a controller

// Inside Controller
$scope.validationCode = 'response returned from server'

If

$scope.validationCode = 1234123412351234

then the ng-pattern would be

ng-pattern="/^1234123412351234$/"

But this isn't working and it seems like I need to create a custom directive which I don't really want

abcf
  • 685
  • 2
  • 10
  • 25
  • Oh...you know what... I think I found a similar question...crap http://stackoverflow.com/questions/494035/how-do-you-pass-a-variable-to-a-regular-expression-javascript?rq=1 – abcf Feb 25 '15 at 23:08

1 Answers1

30

ng-pattern expects a regex expression.

From Angular's documentation about ng-pattern:

Sets pattern validation error key if the value does not match the RegExp pattern expression. Expected value is /regexp/ for inline patterns or regexp for patterns defined as scope expressions.

In other words, you could create a RegExp in the controller:

$scope.pattern = new RegExp(patternFromServer);

and use it:

<input ng-model="foo" ng-pattern="pattern">
New Dev
  • 48,427
  • 12
  • 87
  • 129