RegEx in Angular 2 Form Validators producing different results when argument is a String vs a RegExp class

萝らか妹 提交于 2021-02-16 19:03:29

问题


I'm attempting to validate a basic form element using Angular 2 Form Validators, and the RegEx I'm placing in to Validators.pattern() to match a valid URL is matching patterns that theoretically aren't valid when the argument is a String data type.

// 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)
           ]
     ]
 });

The above RegEx pattern, when placed in to a RegEx101.com (example here) targeting the JavaScript RegEx engine, will not match with the string 'goog'. But, in the template for the example.component.ts class, the pattern does match with a string like 'goog' when the first Validator.pattern(String) is used. I have also had coworkers mention other patterns behaving strangely when inserted as a string, even though the method description in VS Code accepts a String or RegExp class. Why is this?


回答1:


You may use

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

The ^ (at the start) and $ (at the end) will be added by Angular2 automatically (note that you are in charge of properly grouping the pattern in that case, though in this case it is not required).

The most important part here is that you need to double the escaping backslash in the string literal to define a literal backslash that escapes special regex metacharacters.

Also, you do not need to escape / in a regex constructor notation.

Also, you have ([\/\w \.-]*)* that is a very poor pattern: it is the same as [/\\w .-]*, so remove the quantified grouping here.



来源:https://stackoverflow.com/questions/41768721/regex-in-angular-2-form-validators-producing-different-results-when-argument-is

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!