sg552
sg552

Reputation: 1543

Using ng-pattern does not work from controller or JSON

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.

Upvotes: 2

Views: 544

Answers (1)

Oberon
Oberon

Reputation: 200

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:

Upvotes: 1

Related Questions