I am trying to figure how to require both letters and numbers only without any other characters. So literally [a-z]
and ( \d
or [0-9]
) depending what is better way of doing it for numbers.
So if I had a string that requires validation:
$toValidate = 'Q23AS9D0APQQ2'; // It may start with letter or number, both cases possible.
And then if I had validation for it:
return /([a-z].*[0-9])|([0-9].*[a-z])/i.test($toValidate);
I used an i
flag here because it could be that user enters it lowercase or uppercase, it's user preference... So that regex fails... It accepts special characters also, so that is not desired effect.
With the validation above, this passes as well:
$toValidate = 'asdas12312...1231@asda___213-1';
Then I tried something crazy and I don't even know what I have done, so if anyone could tell me beside the correct answer, I'll truly appreciate.
return /([a-z].*\d)+$|(\d.*[a-z])+$/i.test($toValidate);
This seemed to work great. But then when I tried to continue typing letters or numbers after an special character it still validates as true
.
Example:
$toValidate = 'q2IasK231@!@!#_+123';
So please help me understand regularExpressions
better and tell me what is the way to validate the string at the beginning of my question. Letters and numbers expected in the string.