简体   繁体   English

如何限制输入框接受Angular中的特殊字符?

[英]How to restrict input field from accepting special characters in Angular?

I have a input field that should not be blank and should not allow special characters.我有一个不应为空且不允许特殊字符的输入字段。

I have something like this for validation:我有这样的东西用于验证:

if (value === '' || !value.trim()) {
      this.invalidNameFeedback = 'This field can not be blank.';
      return false;
    } else if (!value.match(/[\p{Letter}\p{Mark}]+/gu)) {
      this.invalidNameFeedback = 'This field can not contain special characters.';
      return false;
    }

This allows special characters when entered with alphabets or numbers.当输入字母或数字时,这允许使用特殊字符。 I dont want allow special characters at all.我根本不想允许特殊字符。

You could check the whole value to only match a selected character class and use for example .test()您可以检查整个值以仅匹配选定的字符 class 并使用例如.test()

^[\p{Alphabetic}\p{Mark}\p{Decimal_Number}\p{Connector_Punctuation}\p{Join_Control}]+$

See the regex matches .查看正则表达式匹配

Example例子

if (value === '' || !value.trim()) {
    this.invalidNameFeedback = 'This field can not be blank.';
    return false;
} else if (!/^[\p{Alphabetic}\p{Mark}\p{Decimal_Number}\p{Connector_Punctuation}\p{Join_Control}]+$/u.test(value)) {
    this.invalidNameFeedback = 'This field can not contain special characters.';
    return false;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM