hendrix hendrix - 5 months ago 20
Javascript Question

Validate that a password is alphanumeric with regex JS

I want to validate that an entered password contains letters (no minimum or maximum) and at least 1 number. Ths is my validation so far.

function validate(){

var password = $("#password").val(); //user enters password in text field

if (/^[0-9]{1,}[A-Za-z]{1,}/.test(password)){ //this regex does not quite do what i want
alert("Password is correct");
}
else if (password == null || password.length == 0){
alert("Enter password");
}else{
alert("Wrong password");
}
}
}

Answer

Regex for alphanumeric characters:

/^([a-zA-Z0-9]+)$/

Regex for at least one numeric:

/\d/

Regex for at least one alphabetic:

/[A-Z]/i

You can combine the above into an if statement as follows:

if (/^([a-zA-Z0-9]+)$/.test(password) && /\d/.test(password) &&
    /[A-Z]/i.test(password)) {
    alert("Password is correct");
}