Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use ng-pattern with a variable

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

like image 830
abcf Avatar asked Feb 25 '15 23:02

abcf


1 Answers

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">
like image 150
New Dev Avatar answered Sep 29 '22 10:09

New Dev