All uppercase and lowercase letters, digits, Chinese characters, and half – corner characters except _ (underscore)

The product mentioned this requirement, the application scenario is form verification, at the beginning of the feel very simple, ^_ not to solve? The truth is not that simple. My re validator code:

    Validators.pattern('^[a-zA-Z0-9\u4e00-\u9fa5]+$')
Copy the code

Matches letters, numbers, and Chinese characters. Write it backwards because you are using a validator. What do I write if I want to match the symbol? Look at the requirements:


    Validators.pattern('^[a-zA-Z0-9.-+=~!@#$%^&*(),?;:\'\"\|\u4e00-\u9fa5]+$')
Copy the code

However goose this time even the input sadasdas detected illegal character, why? Because there is a single quotes, double quotes “[] and |, haven’t say, this will also make regular disorder. Searching for a long time on the Internet, no ready-made code – – had to solve their own. Thought for a moment, or use the unicode instead ‘, “, |, [], or use Ascil coding, decisive use Ascil coding, don’t ask why, ask is what I love to. First look at Ascil coding, online pictures are strange, do not understand… Finally one that’s easy to understand.

Validators.pattern('^[a-zA-Z0-9\x21-\x2f\x3a-\x40\x5b-\x60\x7B-\x7F\u4e00-\u9fa5]+$')a5]+$')
Copy the code

X21 – \ x2f \ x3a – \ x40 \ x5b \ x60 \ x7B – \ x7F match all the half Angle character, I want to skip _ to do, see figure _ coding is 5 e, ok, code rewritten as follows:

Validators.pattern('^[a-zA-Z0-9\x21-\x2f\x3a-\x40\x5b-\x5e\x60\x7B-\x7F\u4e00-\u9fa5]+$')
Copy the code

To complete. Hope everyone can avoid (CAI) pit more.