Password Validation Regex

Validate password strength with this comprehensive regular expression pattern that ensures minimum security requirements

BeginnerContact
Regular Expression Pattern
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$
Pattern Breakdown
^Start of string anchor
[a-zA-Z0-9._%+-]+Local part: letters, numbers, dots, underscores, percent, plus, and hyphens (one or more)
@Literal @ symbol
[a-zA-Z0-9.-]+Domain name: letters, numbers, dots, and hyphens (one or more)
\.Literal dot (escaped)
[a-zA-Z]{2,}Top-level domain: letters only, 2 or more characters
$End of string anchor
Test Your Email
Code Examples

javascript

// Password strength validation regex
const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/;

function validatePassword(password) {
  return passwordRegex.test(password);
}

// Usage examples
console.log(validatePassword("MyPass123!")); // true
console.log(validatePassword("SecureP@ssw0rd")); // true
console.log(validatePassword("weak")); // false

python

import re

# Password strength validation pattern
password_pattern = r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$'

def validate_password(password):
    return bool(re.match(password_pattern, password))

# Usage examples
print(validate_password("MyPass123!"))  # True
print(validate_password("SecureP@ssw0rd"))  # True
print(validate_password("weak"))  # False

java

import java.util.regex.Pattern;

public class PasswordValidator {
    private static final String PASSWORD_PATTERN = 
        "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@$!%*?&])[A-Za-z\\d@$!%*?&]{8,}$";
    
    private static final Pattern pattern = Pattern.compile(PASSWORD_PATTERN);
    
    public static boolean validatePassword(String password) {
        return pattern.matcher(password).matches();
    }
    
    public static void main(String[] args) {
        System.out.println(validatePassword("MyPass123!")); // true
        System.out.println(validatePassword("weak")); // false
    }
}
Test Cases
InputExpectedDescription
MyPass123!✓ ValidStrong password with all requirements
SecureP@ssw0rd✓ ValidPassword with special characters
Password1!✓ ValidStandard strong password
Complex#Pass9✓ ValidComplex password with symbols
password✗ InvalidNo uppercase, numbers, or special chars
PASSWORD✗ InvalidNo lowercase, numbers, or special chars
Password✗ InvalidMissing numbers and special chars
Pass1!✗ InvalidToo short (less than 8 characters)
Password123✗ InvalidMissing special characters
Common Use Cases

User Registration Validation

Validate email address format in user registration forms to ensure users enter valid email addresses and avoid issues caused by invalid emails.

// Registration form validation
if (!passwordRegex.test(userPassword)) {
  showError("Please enter a valid password");
}

Pre-send Email Validation

Validate recipient email addresses before sending emails to avoid sending failures due to format errors and improve email delivery rates.

// Password validation
const validPasswords = passwords.filter(password =>
  passwordRegex.test(password)
);

Data Cleaning and Import

Use regular expressions to filter and validate email addresses when importing user data in bulk, ensuring data quality and integrity.

// Password validation
const validUsers = rawData.filter(user =>
  passwordRegex.test(user.password)
);

API Interface Validation

Validate email address format in request parameters within API interfaces to ensure interface robustness and data validity.

// API parameter validation
if (!passwordRegex.test(req.body.password)) {
  return res.status(400).json({error: "Invalid password"});
}
Frequently Asked Questions

Why did my email validation fail?

Common reasons for email validation failure include: email addresses containing special characters, incorrect domain format, missing @ symbol or top-level domain. Please ensure the email format is: username@domain.suffix

Correct format: user@example.com, test.email+tag@domain.co.uk
Incorrect format: user@domain, @domain.com, user.domain.com

Does this regex support internationalized domain names?

The current regex primarily supports ASCII character domains. If you need to support internationalized domain names (IDN), it's recommended to use specialized email validation libraries or more complex regular expressions.

Note: For production environments, it's recommended to combine server-side validation with email confirmation mechanisms to ensure email address validity.

How to handle case sensitivity in email addresses?

The local part of an email address (before @) may be case-sensitive, but the domain part is not case-sensitive. In practice, the entire email address is usually converted to lowercase for processing.

// Normalize email address
const normalizedEmail = email.toLowerCase().trim();

Does passing regex validation mean the email actually exists?

No. Regular expressions can only validate whether the email address format is correct, but cannot verify whether the email actually exists. To verify email authenticity, you need to send confirmation emails or use specialized email verification services.