Reputation: 4136
It doesn't matter how many letters and digits, but string should contain both.
Jquery function $('#sample1').alphanumeric()
will validate given string is alphanumeric or not. I, however, want to validate that it contains both.
Upvotes: 16
Views: 29098
Reputation: 152956
So you want to check two conditions. While you could use one complicated regular expression, it's better to use two of them:
if (/\d/.test(string) && /[a-zA-Z]/.test(string)) {
This makes your program more readable and may even perform slightly better (not sure about that though).
Upvotes: 32
Reputation: 3891
You can use regular expressions
/^[A-z0-9]+$/g //defines captial a-z and lowercase a-z then numbers 0 through nine
function isAlphaNum(s){ // this function tests it
p = /^[A-z0-9]+$/g;
return p.test(s);
}
Upvotes: -1
Reputation: 14783
This is the regex you need
^\w*(?=\w*\d)(?=\w*[A-Za-z])\w*$
and this link explains how you'd use it
http://www.regular-expressions.info/javascript.html
Upvotes: 1