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

1

1 Answer 1

31

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">
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.