How to check a string containing at least one letter and one digit in javascript?

It doesn't matter how many letters and numbers, but the string should contain both.

The jQuery function $('#sample1').alphanumeric()will check the given string as alphanumeric or not. However, I want to verify that it contains both.

+5
source share
4 answers

So you want to check two conditions. Although you can use one complex regular expression, it is better to use two of them:

if (/\d/.test(string) && /[a-zA-Z]/.test(string)) {

This makes your program more readable and may even improve slightly (but not sure about that).

+14
source

This is the regular expression you need

^\w*(?=\w*\d)(?=\w*[A-Za-z])\w*$

and this link explains how you use it.

http://www.regular-expressions.info/javascript.html

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

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);
}
0
source

All Articles