首页 文章

Angular 2中的RegEx形式验证器在参数是String与RegExp类时产生不同的结果

提问于
浏览
3

我'm attempting to validate a basic form element using Angular 2 Form Validators, and the RegEx I' m放入 Validators.pattern() 以匹配有效的URL是匹配模式,当参数是String数据类型时,理论上这些模式无效 .

// example.component.ts

this.exampleForm = fb.group({
    // The patterns below will match most URL structures, and are exactly the same
    const reg = '^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$';
    const patt = new RegExp(/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/);

    'url': ['', [
                Validators.required,
                // Matches many unintended patterns
                Validators.pattern(reg),
                // Works as intended
                Validators.pattern(patt)
           ]
     ]
 });

当置于针对JavaScript RegEx引擎的RegEx101.com(示例here)中时,上述RegEx模式将与字符串'goog'不匹配 . 但是,在 example.component.ts 类的模板中,当使用第一个 Validator.pattern(String) 时,模式与'goog'之类的字符串匹配 . 我也有同事提到其他模式在插入字符串时表现得很奇怪,即使VS Code中的方法描述接受String或RegExp类 . 为什么是这样?

1 回答

  • 3

    你可以用

    const reg = '(https?://)?([\\da-z.-]+)\\.([a-z.]{2,6})[/\\w .-]*/?';
    

    Angular2会自动添加 ^ (在开始时)和 $ (在结尾处)(请注意,在这种情况下,您负责正确分组模式,但在这种情况下不需要) .

    这里最重要的部分是你需要将字符串文字中的转义反斜杠加倍,以定义一个逃避特殊正则表达式元字符的文字反斜杠 .

    此外,您不需要以正则表达式构造函数表示法转义 / .

    此外,你有 ([\/\w \.-]*)* 这是一个非常糟糕的模式:它与 [/\\w .-]* 相同,所以在这里删除量化分组 .

相关问题