How to validate a letter and whitespace only input via JavaScript regular expression

后端 未结 6 1360
甜味超标
甜味超标 2021-01-04 10:55

I have an input type=\"text\" for names in my HTML code. I need to make sure that it is a string with letters from \'a\' to \'z\' and \'A\' to \'Z\' only, along

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-04 11:47

    /^[A-Z ]+$/i.test(x) does the trick according to your specification, but if I were you, I'd add dashes, i.e. /^[-A-Z ]+$/i.test(x), because double-barreled names are quite common. Of course, I'd suggest later revisiting this once JS gets unicode word detection support in its RegExp to support even more names.

    EDIT: Actually, if you want to make sure the name is not ill-formed, e.g. there's at least the first name and the last name and there are no extra spaces, you could do something like this: /^(?:[-A-Z]+ )+[-A-Z]+$/i.test(x). I also just remembered you might want to include dots as well, e.g "Henry Jr. Jones". Combined to the previous one this would be: /^(?:[-A-Z]+\.? )+[-A-Z]+$/i.test(x).

提交回复
热议问题