2

我有这个代码,它只接受 6 位数字:

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

并且正则表达式值是从 JSON 文件中设置的,如下所示:

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

这是输出:

在此处输入图像描述

现在的问题是,如果我在 ID 字段中键入 6 位数字,错误消息不会消失。我输入的任何数字都不会使其工作。但是,如果我将正则表达式硬编码为这样的ng-pattern属性:

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

在此处输入图像描述

它会起作用的!错误消息将消失。我还像这样从控制器测试了它:

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

它也不起作用。有谁知道是什么问题?请提前帮助和感谢。

4

1 回答 1

1

RegExp 构造函数可以用两种方式表示:

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

注意字符串表示法没有 / 字符,但文字表示法有。

如果包含 / 字符,ng-pattern 会自动将字符串输入转换为文字表示法。如果它检测到一个没有包含 / 字符的字符串,它会将其包装在 ^ 和 $ 字符中。例如"abc",将转换为new RegExp('^abc$')"/abc/i"将评估为new RegExp(/abc/i).

参考:

于 2016-09-11T04:44:00.743 回答