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})?$/"
Michael Warner
  • 3,879
  • 3
  • 21
  • 45

2 Answers2

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.

Washington Guedes
  • 4,254
  • 3
  • 30
  • 56
1

Just add the constants to a $scope variable

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

and then in html

ng-pattern=myPattern
Simon Schüpbach
  • 2,625
  • 2
  • 13
  • 26