I know how to do a regex to validate if it's just letter number without no white spaces:
/^[0-9a-zA-Z]+$/
but how do I add to this regex also such that it cannot contain just numbers, so for example this is not valid:
08128912382
Any ideas?
"Must contain only letters and numbers and at least one letter" is equivalent to "must contain a letter surrounded by numbers or letters":
/^[0-9a-zA-Z]*[a-zA-Z][0-9a-zA-Z]*$/
I would like to add that this answer shows a way you can think about the problem so writing the regexp is simpler. It is not meant to be the best solution to the problem. I just took what you had and gave it a nudge in the right direction.
With several more nudges, you end up with other different answers (posted by ZER0, Tomalak and OGHaza respectively) :
You could notice that if there is a letter in the first or last group, the middle part is satisfied. In other words, since you have the middle part, you don't need to allow letters in the first or last part (but not both!):
/^[0-9]*[a-zA-Z][0-9a-zA-Z]*$/
- some numbers, followed by a letter, followed by some more numbers and letters/^[0-9a-zA-Z]*[a-zA-Z][0-9]*$/
- equivalent if you read from the endKnowing about lookaheads you can assert that there is at least one letter in the string:
/^(?=.*[a-z])/
- matches the start of any string that contains at least 1 letterOr the other way around, as you expressed it, assert that there aren't only numbers in the string:
/^(?!\d+$)/
- matches the start of any string which doesn't contain just digitsThe 2nd and 3rd solutions should also be combined with your original regexp that validates that the string contains only the characters you want it to (letters and numbers)
I for one am particularly fond of the 2nd solution which is i believe the fastest of all attempted so far.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With