Sahal
Sahal

Reputation: 4136

How to validate a string which contains at least one letter and one digit in javascript?

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

Answers (4)

user123444555621
user123444555621

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

symcbean
symcbean

Reputation: 48357

/([0-9].*[a-z])|([a-z].*[0-9])/

Upvotes: 2

Drake
Drake

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

James Gaunt
James Gaunt

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

Related Questions