I know everyone has come through here and told you to use regular expressions (partly because you started with that). Please don't. There are times in which regular expressions are the better choice. That is rare though, they are way overused, and this is not one of those times. The following code is way more readable than the regex mess in the accepted answer.
This code also allows you to test each condition individually and give customized errors to the user.
function isValidPassword(str)
{
return str.length == 8 &&
digitCount(str) >= 2 &&
hasLetters(str) &&
hasOnlyLettersAndDigits(str);
}
function isAsciiCodeLetter(asciiCode)
{
return (65 <= asciiCode && asciiCode <= 90) ||
(97 <= asciiCode && asciiCode <= 122);
}
function isAsciiCodeDigit(asciiCode)
{
return 48 <= asciiCode && asciiCode <= 57;
}
function hasLetters(str)
{
for (var i = 0, len = str.length; i < len; i++)
{
if (isAsciiCodeLetter(str.charCodeAt(i)))
return true;
}
return false;
}
function hasOnlyLettersAndDigits(str)
{
for (var i = 0, len = str.length; i < len; i++)
{
var asciiCode = str.charCodeAt(i);
if (!isAsciiCodeLetter(str.charCodeAt(i)) &&
!isAsciiCodeDigit(str.charCodeAt(i)))
{
return false;
}
}
return true;
}
function digitCount(str)
{
var count = 0;
for (var i = 0, len = str.length; i < len; i++)
{
if (isAsciiCodeDigit(str.charCodeAt(i)))
{
count++;
}
}
return count;
}
Don't use regex, but if you're dead set on using regex, match on [0-9].*[0-9]
for 2 digits, [a-zA-Z]
for a character, and ^[0-9a-zA-Z]{8}$
for the length and characters/digits only requirement. That's at least sort of readable:
function isValidPassword(str)
{
var atLeastTwoDigits = new RegExp("[0-9].*[0-9]");
var atLeastOneCharacter = new RegExp("[a-zA-Z]");
var onlyEightCharactersAndDigits = new RegExp("^[0-9a-zA-Z]{8}$");
return atLeastTwoDigits.test(str) &&
atLeastOneCharacter.test(str) &&
onlyEightCharactersAndDigits.test(str);
}
Test cases:
alert(isValidPassword("asdfasdf")); //false
alert(isValidPassword("asdfasd4")); //false
alert(isValidPassword("7sdfasd4")); //true
alert(isValidPassword("asdfas`f")); //false
alert(isValidPassword("asd3a4df-")); //false
alert(isValidPassword("asd3a4f-")); //false
alert(isValidPassword("asd3a4df")); //true
alert(isValidPassword("12345678")); //false
alert(isValidPassword("1helloo5")); //true
alert(isValidPassword("helloos5")); //false
alert(isValidPassword("45345345")); //false
alert(isValidPassword("123`567d")); //false