First of all this is not a duplicate (as far as I know).
What I exactly want is to allow the user to have a username (profile name) that contains only valid characters, which in my case, are letters of all languages, as well as spaces. But at the same time prevent numbers, symbols (like !@#$%^&*()|\/?'";:=+-_.<>,~
), other uncommon symbols (like ©®♣♥♠♩¸¸♪·¯·♫
), new-line, tab, and similar characters, emojis, and every single character that is not normal to be seen in a name...
Well, to make it clearer, I want to implement the exact same profile name system as Facebook for example.
I'm using JS (Node), and I tried regular expressions so far, but I don't thing it's sane to type every single range of valid characters in unicode in that expression is it?! I'll not even try thinking about what would that cause for me in future when I need to edit those ranges...
Is there any libraries that provide a way to do that exactly? If no, what other options do I have?
Any help is appreciated!
For English only you could use a simple character class such as /^[a-zA-Z ]$/
or with word char /^[\w ]$/
. There is a Unicode equivalent for this:
/^[\p{L}\p{M}\p{Zs}]{2,30}$/u
Explanation:
\p{L}
- denotes a letter char in any language\p{M}
- denotes a mark (accent etc)\p{Zs}
- denotes a space char, such as regular space
and Japanese space char
In case you want to prevent space at the start and end, use these negative lookaheads:
/^(?!\p{Zs})(?!.*\p{Zs}$)[\p{L}\p{M}\p{Zs}]{2,30}$/u
Example function:
function validateName(name) {
return /^[\p{L}\p{M}\p{Zs}]{2,30}$/u.test(name);
}
See a demo at https://regex101.com/r/A4QDIf/1
See docs on Unicode regex: https://javascript.info/regexp-unicode