2

I have this code which will only accept 6 digit numeric:

<input
   ng-pattern="{{widget.regex}}" 
   name="{{widget.id}}">
{{widget.regex}}

<span ng-if="(myForm[item.id].$touched === true && myForm[item.id].$valid === false)" class="help-block">
    <div ng-message="pattern">Enter 6 digit ID</div>
</span>

and the regex value is being set from JSON file like this:

{
  "items": [
    {
      "id": "customerID",
      "label": "Enter ID",
      "required": "yes",
      "regex": "/^[0-9]{6,6}$/i"
    },
    {
      "id": "customerEmail",
      "label": "Email",
      "required": "yes"
    }
  ]
},

and here's the output:

enter image description here

Now the problem is, if I keyin 6 digit numeric in the ID field, the error message wont go away. Any number I enter will not make it work. However if I hardcoded the regex to ng-pattern attribute like this:

<input
   ng-pattern="/^[0-9]{6,6}$/i" 
   name="{{widget.id}}">
{{widget.regex}}

<span ng-if="(myForm[item.id].$touched === true && myForm[item.id].$valid === false)" class="help-block">
    <div ng-message="pattern">Enter 6 digit ID</div>
</span>

enter image description here

It will work! The error message will go away. I also tested it from controller like this:

vm.regex = new RegExp('/^[0-9]{6,6}$/i');

and it does not worked too. Anyone know what is the problem? Please help and thanks in advance.

sg552
  • 1,521
  • 6
  • 32
  • 59

1 Answers1

1

The RegExp constructor can be expressed in two ways:

new RegExp('ab+c', 'i');   //string notation
new RegExp(/ab+c/i);   //literal regex notation

Notice how the string notation does not have the / character, but the literal notation does.

ng-pattern automatically converts the string input to literal notation if the / characters are included. If it detects a string without enclosing / characters, it wraps it in ^ and $ characters. E.g. "abc" will be converted to new RegExp('^abc$') but "/abc/i" will evaluate to new RegExp(/abc/i).

References:

Oberon
  • 200
  • 1
  • 9
  • Changing `"regex": "/^[0-9]{6,6}$/i"` to `"regex": "[0-9]{6,6}"` solved the problem. Thank you very much :) – sg552 Sep 11 '16 at 05:25
  • but why does hardcoding the regex to `ng-pattern` does worked though? Isn't it will messed up my regex from `/^[0-9]{6,6}$/i` to `^/^[0-9]{6,6}$/i$`? – sg552 Sep 11 '16 at 14:59
  • 1
    From the ng-pattern docs: If the expression evaluates to a RegExp object, then this is used directly. So angular is smart enough to know `ng-pattern = "/^[0-9]{6,6}$/i"` will convert directly to `new RegExp(/^[0-9]{6,6}$/i)`. Answer has been edited to reflect this. – Oberon Sep 11 '16 at 21:30