sg552 sg552 - 2 months ago 15
AngularJS Question

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="(rapiForm[item.id].$touched === true && rapiForm[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="(rapiForm[item.id].$touched === true && rapiForm[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.

Answer

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 and wraps it in ^ and $ characters. E.g. "abc" will be converted to new RegExp('^abc$')

References:

Comments