Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 676
Sahal Avatar asked Aug 16 '11 08:08

Sahal


People also ask

How do you check if a string contains at least one character in JS?

To check if a string contains any letter, use the test() method with the following regular expression /[a-zA-Z]/ . The test method will return true if the string contains at least one letter and false otherwise. Copied!

How do you check if a character in a string is a digit or letter JavaScript?

To check if a character is a letter, call the test() method on the following regular expression - /^[a-zA-Z]+$/ . If the character is a letter, the test method will return true , otherwise false will be returned.

How do you check if a string contains only alphabets and numbers in JavaScript?

Use the test() method on the following regular expression to check if a string contains only letters and numbers - /^[A-Za-z0-9]*$/ . The test method will return true if the regular expression is matched in the string and false otherwise. Copied!

How do I check if a string contains a digit?

To find whether a given string contains a number, convert it to a character array and find whether each character in the array is a digit using the isDigit() method of the Character class.


2 Answers

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

like image 94
user123444555621 Avatar answered Sep 18 '22 17:09

user123444555621


/([0-9].*[a-z])|([a-z].*[0-9])/
like image 42
symcbean Avatar answered Sep 20 '22 17:09

symcbean