JAVASCRIPT

Validate Strong Password

Enforce strong password policies using a JavaScript regex to check for minimum length, uppercase, lowercase, numbers, and special characters.

function isStrongPassword(password) {
  // Must contain at least one uppercase letter, one lowercase letter,
  // one number, one special character, and be at least 8 characters long.
  const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/;
  return passwordRegex.test(password);
}

// Usage:
console.log(isStrongPassword('MyStrongP@ss1')); // true
console.log(isStrongPassword('weakpassword'));  // false
How it works: The `isStrongPassword` function employs a complex regex to validate password strength. It uses positive lookaheads `(?=...)` to assert that the password contains at least one lowercase letter, one uppercase letter, one digit, and one specified special character. Finally, `[A-Za-z\d@$!%*?&]{8,}$` ensures the overall string is at least 8 characters long and only contains allowed characters.

Need help integrating this into your project?

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

Hire DigitalCodeLabs