1

--Short Version--

How do you get ng-pattern to use regex from angular constants?

--Long Version--

I'm working on a huge Angular 1 project and we have multiple forms. A lot of these forms have the same fields like Zip and Phone Number. I wanted to look for a consistent way to use ng-pattern but have the regex in one location for consistency. I want to use angular constants for this but I can't get ng-pattern to take the value and I can't figure out why.

--What I've done--

I did find this answer Angularjs dynamic ng-pattern validation for placing regex dynamically into ng-pattern and I tried that but that method didn't seem to work for angular constants.

I've tried storing the regex as strings and converting it in the HTML. I've tried using a function that returns the regex value.

--jsfiddle of the issue--

https://jsfiddle.net/Michael_Warner/692deLsb/8/

The issue goes down to this line of code.

ng-pattern="patterns.zip"

If I embed the regex into ng-pattern directly then it will work as you can see in the fiddle

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

2 Answers 2

4

You can do it in two ways:

1: As string literal, when you must double slashes:

.constant("formPattern", {
    zip: new RegExp("^\\d{5}(?:-\\d{4})?$")
})

2: As regular expression:

.constant("formPattern", {
    zip: /^\d{5}(?:-\d{4})?$/
})

Both worked in your fiddle.

Sign up to request clarification or add additional context in comments.

Comments

1

Just add the constants to a $scope variable

$scope.myPattern = /^\d{5}(?:-\d{4})?$/;

and then in html

ng-pattern=myPattern

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.