Home » JavaScript Examples » Validate Password with Regex Pattern in JS

Validate Password with Regex Pattern in JS

You can use JavaScript to validate a password with the given regex pattern

Regex Password Patterns:


// Minimum eight characters, at least one letter and one number:

"^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$"

// Minimum eight characters, at least one letter, one number and one special character:

"^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]{8,}$"

// Minimum eight characters, at least one uppercase letter, one lowercase letter and one number:

"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$"

// Minimum eight characters, at least one uppercase letter, one lowercase letter, one number and one special character:

"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$"

// Minimum eight and maximum 10 characters, at least one uppercase letter, one lowercase letter, one number and one special character:

"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,10}$"


Validate Password with Regex – Javascript Code Example


Full HTML code example that includes a simple form for validating a password using JavaScript:

code snippet/ example:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Password Validation</title>
    <script>
        function validatePassword() {
            const passwordInput = document.getElementById("password");
            const password = passwordInput.value;

            // Define the regex pattern for the password
            const passwordPattern = /^(?=.*[A-Za-z])(?=.*\d).{8,}$/;

            // Test if the password matches the pattern
            if (passwordPattern.test(password)) {
                alert("Password is valid!");
            } else {
                alert("Password is invalid. It should be at least eight characters long and contain at least one letter and one number.");
            }
        }
    </script>
</head>
<body>
    <h1>Password Validation</h1>
    <form>
        <label for="password">Password:</label>
        <input type="password" id="password" name="password" required>
        <br>
        <button type="button" onclick="validatePassword()">Validate Password</button>
    </form>
</body>
</html>