【问题标题】:How can I modify this validation logic to be able to allow characters and some special characters too to be entered?如何修改此验证逻辑以允许输入字符和一些特殊字符?
【发布时间】:2020-01-26 01:45:26
【问题描述】:

目前,只允许在字段中输入字符,否则会在代码中引发下面提到的错误。如何修改此逻辑以添加字母以及一些特殊字符,如连字符、撇号等?

    function NameValidate(control: FormControl) {
  if (typeof control.value !== 'string' || !/^[a-zA-Z\s]+$/g.test(control.value)) {
    return {
      error: 'Only characters allowed'
    };
  } else {
    return null;
  }
}

【问题讨论】:

    标签: javascript angular typescript user-interface angular6


    【解决方案1】:

    我相信这里的关键是 if 语句

    if (typeof control.value !== 'string' || !/^[a-zA-Z\s]+$/g.test(control.value))
    

    这句话本质上说“如果控制值不是字符串或不匹配正则表达式/^[a-zA-Z\s]+$/,则返回错误。

    因此,为了也允许特殊字符,您需要调整正则表达式以允许这些字符。例如,要允许使用连字符,请将正则表达式更改为 /^[a-zA-Z\s-]+$/(注意括号内添加的 -。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-28
      • 2014-07-25
      • 1970-01-01
      • 2020-09-15
      • 1970-01-01
      • 1970-01-01
      • 2020-09-05
      相关资源
      最近更新 更多