angular中的特殊字符校验方法

前端开发中,对输入的特殊字符校验必不可少,但不同的输入需要校验的特殊字符也不同,我们通常会写一个通用的可定制特殊字符的校验方法。

下面是angular中的对定制特殊字符校验的方法。

static specialcodeCustom(customStr: string): any {
    return (control: AbstractControl): any => {
      if (!control.value) {
        return;
      }
      const special = new RegExp(`[${customStr}]`);
      if (special.test(control.value)) {
        return { specialcode: customStr };
      }
    };
  }

但是今天发现了一个问题,在定制特殊字符为:',、#%?[]|:”+;=&'如果直接输入specialcodeCustom(',、#%?[]|:”+;=&')发现无法校验]及其以后的特殊字符。因为我们这里的]和前面的[匹配上了,导致这个正则表达式无法正确解析,那应该怎么写呢?直接上正确答案(方便起见直接写了一个简单的html页面):

html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Documenttitle>
head>
<body>
    <input type="text" id="test">
    <script>
        const test = document.getElementById('test');
        const customStr = ',、#<>%?\\[\\]|:”+;=&';
        const special = new RegExp(`[${customStr}]`);
        test.onchange = () => {
            console.log(test.value);
            console.log(special);
            console.log(special.test(test.value));
        }
    script>
body>
html>

',、#%?\\[\\]|:”+;=&'需要在[]字符前面加上两个\\才可以。

我们来看下的描述:

支持两种方式:字面量和构造函数。

字面量:由斜杠 (/) 包围而不是引号包围

构造函数的字符串参数:由引号而不是斜杠包围

/ab+c/i; //字面量形式
new RegExp("ab+c", "i"); // 首个参数为字符串模式的构造函数
new RegExp(/ab+c/, "i"); // 首个参数为常规字面量的构造函数

上面三种创建的是同一个正则表达式。

我们用字面量定义的时候对[需要一层转义\[,所以在用字符串构造时就需要多一层转义。

以上,记录下遇到bug的修正结果啦!

相关阅读

添加新评论