← Back to all snippets
JAVASCRIPT

Validate Strong Password Format

Implement strong password validation in JavaScript using regex, requiring minimum length, uppercase, lowercase, numbers, and special characters for enhanced security.

function isStrongPassword(password) {
  // At least 8 characters long
  // Contains at least one uppercase letter
  // Contains at least one lowercase letter
  // Contains at least one number
  // Contains at least one special character (e.g., !@#$%^&*()_+={}[ ]|:;"'<>,.?/~`)
  const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*()_+={}\[\]|:;"'<>,.?/~`])[A-Za-z\d!@#$%^&*()_+={}\[\]|:;"'<>,.?/~`]{8,}$/;
  return passwordRegex.test(password);
}

// Example usage:
console.log(isStrongPassword("MyPass123!")); // true
console.log(isStrongPassword("weakpass")); // false (no uppercase, no special char, too short if min 8)
console.log(isStrongPassword("Password123")); // false (no special char)
console.log(isStrongPassword("password!@#")); // false (no uppercase)
console.log(isStrongPassword("P1!")); // false (too short)
How it works: This snippet provides a JavaScript function to validate password strength using a single regular expression. It enforces criteria such as a minimum length of 8 characters and the presence of at least one uppercase letter, one lowercase letter, one digit, and one special character. This is achieved using positive lookaheads `(?=...)` to assert these conditions without consuming characters.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs