0

I created an angular Value service that holds a regex than I attached it to the controller instance i.e.

myService.value('regexValue' {PASSWORD_REGEX: /passwordregex/})


myController(regexValue) { 
    this.regexValue = regexValue.PASSWORD_REGEX;  
}

then I am trying to use this value in an input field data-ng-pattern attribute

<input type="password" data-ng-pattern="myController.regexValue.PASSWORD_REGEX">

this however does not seem to work with the ng-pattern directive.

My question is how can I get this to work?

Tiago Roldão
  • 10,629
  • 3
  • 29
  • 28
Subtubes
  • 15,851
  • 22
  • 70
  • 105

2 Answers2

2

Your theory is correct. ng-pattern accepts both a string representation of a pattern, an inline pattern or a scoped variable. The only problem is that you are scoping regexValue.PASSWORD_REGEX under the controller as controller.regexValue, and then thrying to access controller.regexValue.PASSWORD_REGEX.

Either do:

myController(regexValue) { 

    this.regexValue = regexValue.PASSWORD_REGEX;  
}

<input type="password" data-ng-pattern="myController.regexValue">

or

myController(regexValue) { 
    this.regexValue = regexValue;  
}

<input type="password" data-ng-pattern="myController.regexValue.PASSWORD_REGEX">

Working fiddle: http://jsfiddle.net/yrq18bbh/3/

Tiago Roldão
  • 10,629
  • 3
  • 29
  • 28
1

ng-pattern wants a string representation of the pattern (without the /), so you can get that from your regex by accessing the source property:

<input type="password" data-ng-pattern="myController.regexValue.PASSWORD_REGEX.source">

console.log(/foo+bar*?/.source)
mkoryak
  • 57,086
  • 61
  • 201
  • 257
  • If you look at this sample it shows the `/` in there http://stackoverflow.com/questions/19827570/validate-natural-input-number-with-ngpattern – Subtubes Apr 22 '15 at 00:11
  • This is only true for older versions of angularJS, and has since been rectified (after 1.3) – Tiago Roldão Apr 22 '15 at 09:57