13

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.

J. Steen
  • 15,470
  • 15
  • 56
  • 63
Sahal
  • 4,046
  • 15
  • 42
  • 68
  • possible duplicate of [RegEx to make sure that the string contains at least one lower case char, upper case char, digit and symbol](http://stackoverflow.com/questions/1559751/regex-to-make-sure-that-the-string-contains-at-least-one-lower-case-char-upper-c) – Felix Kling Aug 16 '11 at 08:10
  • Your question is not 100% clear: does the string need to be alphanumeric? Or would '#sample1' be valid? – user123444555621 Aug 16 '11 at 08:33

4 Answers4

29

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).

user123444555621
  • 148,182
  • 27
  • 114
  • 126
  • if((/\d/.test(string) || /[a-zA-Z]/.test(string)) === false) { alert('Field has no Alphanumeric characters.'); } – drooh Aug 23 '19 at 23:13
2
/([0-9].*[a-z])|([a-z].*[0-9])/
symcbean
  • 47,736
  • 6
  • 59
  • 94
1

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

James Gaunt
  • 14,631
  • 2
  • 39
  • 57
-1

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);
}
Drake
  • 3,851
  • 8
  • 39
  • 48