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.
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!
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.
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!
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.
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).
/([0-9].*[a-z])|([a-z].*[0-9])/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With