Reputation: 2149
I want to validate a form field by checking of the input contains any letters. All other characters and numbers should be allowed. I'm quite bad at regular expressions, and I can't find a correct solution anywhere.
I've tried this:
/[^A-Za-z]/g
but this only returns false if the string consists of only letters (i.e. 432ad32d should return false as well).
Could anyone tell me how to do this?
Upvotes: 1
Views: 1266
Reputation: 21380
You forgot about start and end markers. Also you don't need g
flag.
/^[^A-Za-z]*$/
Anyway, that's strange as I can enter ciryllic letters still.
Upvotes: 0
Reputation: 5619
/[^A-Za-z]/
This regex matches a single non-letter, which isn't very useful. Yura Yakym's answer matches the beginning of the string, any number of non-letters, and then the end of the string, which is useful when it matches: it means your string contains only those things.
Another useful regex is:
/[A-Za-z]/
This matches a single letter, which is useful when it doesn't match: it means your string does not contain any letters at all.
For your question in general, "how can I ensure a string lacks letters?", I would use that second regex: I would try to match a letter, and hopefully fail to do so. For input validation though, I'd prefer a regex that describes all possible valid inputs. If /^[^A-Za-z]*$/
does so, then use that. If you have additional requirements, add those to it. Don't have multiple "no letters? OK. no non-dash special characters? OK." ... well, unless you want to provide error messages precisely about such things.
Upvotes: 2
Reputation: 51330
Using a whitelist of allowed characters is the best approach in your case:
/^[-+\d(), ]+$/
Unicode has many things it calls a letter, better not mess with that in the first place. And JavaScript regexes aren't well suited for handling these (they lack things like \p{L}
for instance unless you use an external library).
Also, by using the whitelist approach you can be sure about the kinds of inputs which will be accepted by your form. You can't predict the kind of mess users could input otherwise. Think about things like this:
TO͇̹̺ͅƝ̴ȳ̳ TH̘Ë͖́̉ ͠P̯͍̭O̚N̐Y̡ H̸̡̪̯ͨ͊̽̅̾̎Ȩ̬̩̾͛ͪ̈́̀́͘ ̶̧̨̱̹̭̯ͧ̾ͬC̷̙̲̝͖ͭ̏ͥͮ͟Oͮ͏̮̪̝͍M̲̖͊̒ͪͩͬ̚̚͜Ȇ̴̟̟͙̞ͩ͌͝S̨̥̫͎̭ͯ̿̔̀ͅ
:-)
Upvotes: 2
Reputation: 26434
You need to include anchors
/^[^A-Za-z]+$/g
This will ensure the string starts and ends with one or more numbers/special characters
Upvotes: 0