当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - 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:

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>

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.

网友答案:

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:

  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
  • https://docs.angularjs.org/api/ng/directive/ngPattern
分享给朋友:
您可能感兴趣的文章:
随机阅读: