Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
365 views
in Technique[技术] by (71.8m points)

javascript - Test if string contains only letters (a-z + é ü ö ê å ø etc..)

I want to match a string to make sure it contains only letters.

I've got this and it works just fine:

var onlyLetters = /^[a-zA-Z]*$/.test(myString);

BUT

Since I speak another language too, I need to allow all letters, not just A-Z. Also for example:

é ü ? ê ? ?

does anyone know if there is a global 'alpha' term that includes all letters to use with regExp? Or even better, does anyone have some kind of solution?

Thanks alot

EDIT: Just realized that you might also wanna allow '-' and ' ' incase of a double name like: 'Mary-Ann' or 'Mary Ann'

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I don’t know the actual reason for doing this, but if you want to use it as a pre-check for, say, login names oder user nicknames, I’d suggest you enter the characters yourself and don’t use the whole ‘alpha’ characters you’ll find in unicode, because you probably won’t find an optical difference in the following letters:

А ≠ A ≠ Α  # cyrillic, latin, greek

In such cases it’s better to specify the allowed letters manually if you want to minimise account faking and such.

Addition

Well, if it’s for a field which is supposed to be non-unique, I would allow greek as well. I wouldn’t feel well when I force users into changing their name to a latinised version.

But for unique fields like nicknames you need to give your other visitors of the site a hint, that it’s really the nickname they think it is. Bad enough that people will fake accounts with interchanging I and l already. Of course, it’s something that depends on your users; but to be sure I think it’s better to allow basic latin + diacritics only. (Maybe have a look at this list: Latin-derived_alphabet)

As an untested suggestion (with ‘-’, ‘_’ and ‘ ’):

/^[a-zA-Z-_ ’'‘?D????????T???e??????????t?????????????????????Y?????????????????????y??áà??ǎ?ā?????????????????Déè?ê?ě?ē???????????áàa?ǎ?ā?????????????????eéè?ê?ě?ē??????????????Iíì???ǐ?ī?????????????N?N?????óò??ǒ?ō???????????íìi??ǐ?ī??????????????ńn?ň???óò??ǒ?ō?????????????????????Túù?üǔ?ū???????????Y?????????????????????????túù?üǔ?ū???????????y??????????]$/.test(myString)

Another edit: I have added the apostrophe for people with names like O’Neill or O’Reilly. (And the straight and the reversed apostrophe for people who can’t enter the curly one correctly.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...