简体   繁体   中英

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()

^[\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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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