Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Password Strength Validator Laravel Package

rollerworks/password-strength-validator

Symfony Validator password strength constraints with two approaches: validate by strength levels (weak/medium/strong) or by explicit requirements (letters, mixed case, numbers, special chars). PHP 8.4+ and Symfony 7.4+.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:
    composer require rollerworks/password-strength-validator
    
  2. Register the validator in your Symfony service container (if not using the bundle):
    // config/services.yaml
    Symfony\Component\Validator\ValidatorBuilder:
        methods:
            addValidatorService: ['@rollerworks.password_strength_validator']
    
  3. First use case: Validate a password field in a form:
    use Rollerworks\PasswordStrengthValidator\Constraints as PasswordAssert;
    
    class UserType extends AbstractType {
        public function buildForm(FormBuilderInterface $builder, array $options) {
            $builder
                ->add('password', TextType::class, [
                    'constraints' => [
                        new PasswordAssert\ValidPassword([
                            'message' => 'Password is too weak',
                            'minStrength' => 'medium'
                        ])
                    ]
                ]);
        }
    }
    

Key Starting Points

  • Predefined strength levels: weak, medium, strong, very_strong (configurable in config/packages/rollerworks_password_strength.yaml).
  • Custom rules: Combine with PasswordAssert\PasswordStrength for granular control.
  • Symfony Validator integration: Works seamlessly with Symfony’s validation system (e.g., ValidatorInterface).

Implementation Patterns

Common Workflows

  1. Form Validation:

    // In a controller or form type
    $validator = $this->get('validator');
    $errors = $validator->validate($user, [
        new PasswordAssert\ValidPassword(['minStrength' => 'strong'])
    ]);
    
  2. API/Command Validation:

    use Symfony\Component\Validator\Validator\ValidatorInterface;
    
    class RegisterUserCommand {
        public function __construct(
            private ValidatorInterface $validator
        ) {}
    
        public function execute(string $password) {
            $errors = $this->validator->validate($password, [
                new PasswordAssert\PasswordStrength([
                    'minLength' => 12,
                    'maxLength' => 32,
                    'requirements' => [
                        'letters' => true,
                        'numbers' => true,
                        'specialChars' => true,
                    ]
                ])
            ]);
            // Handle errors...
        }
    }
    
  3. Dynamic Strength Levels:

    // Adjust strength based on user role (e.g., admin vs. regular)
    $constraint = new PasswordAssert\ValidPassword([
        'minStrength' => $user->isAdmin() ? 'very_strong' : 'medium'
    ]);
    

Integration Tips

  • Combine with other constraints:
    new PasswordAssert\ValidPassword([
        'minStrength' => 'medium',
        'message' => '{{ value }} is not strong enough.',
    ]),
    new NotBlank(),
    new Length(['min' => 8]),
    
  • Customize strength levels via config:
    # config/packages/rollerworks_password_strength.yaml
    rollerworks_password_strength:
        strength_levels:
            weak:
                minLength: 6
                requirements:
                    letters: true
            medium:
                minLength: 10
                requirements:
                    letters: true
                    numbers: true
    
  • Use in DTOs (e.g., with Symfony Messenger or API Platform):
    use Rollerworks\PasswordStrengthValidator\Constraints as PasswordAssert;
    
    class RegisterDto {
        #[PasswordAssert\ValidPassword(['minStrength' => 'strong'])]
        public string $password;
    }
    

Gotchas and Tips

Pitfalls

  1. Missing NotBlank: The validator does not enforce non-empty passwords. Always pair with:

    new NotBlank(),
    new PasswordAssert\ValidPassword(...),
    

    Symptom: Empty passwords pass validation silently.

  2. Case Sensitivity in Requirements:

    • specialChars checks for non-alphanumeric characters (e.g., !@#).
    • letters is case-insensitive by default (use uppercaseLetters/lowercaseLetters for stricter checks).
  3. Config Overrides:

    • Strength levels defined in config/packages/... override defaults but do not merge with them. Test thoroughly after changes.
  4. Performance:

    • Avoid validating passwords in loops or high-frequency contexts (e.g., bulk imports). Cache or defer validation where possible.

Debugging

  • Enable Symfony’s validation debug mode:

    # config/packages/validator.yaml
    framework:
        validator:
            debug: true
    

    Output: Detailed error messages with failed rules.

  • Inspect strength levels:

    $validator = new \Rollerworks\PasswordStrengthValidator\PasswordStrengthValidator();
    $score = $validator->getPasswordStrengthScore('P@ssw0rd');
    // Returns an array with scores for each requirement.
    

Extension Points

  1. Custom Validators: Extend \Rollerworks\PasswordStrengthValidator\PasswordStrengthValidator to add logic (e.g., dictionary checks):

    use Rollerworks\PasswordStrengthValidator\PasswordStrengthValidator as BaseValidator;
    
    class CustomPasswordValidator extends BaseValidator {
        public function validate($value, Constraint $constraint) {
            if ($this->isCommonPassword($value)) {
                $this->context->buildViolation($constraint->commonPasswordMessage)
                    ->addViolation();
            }
            parent::validate($value, $constraint);
        }
    }
    

    Register it as a service alias.

  2. Override Strength Calculations: Replace the default PasswordStrengthValidator with a decorated version:

    services:
        rollerworks.password_strength_validator:
            class: App\Validator\CustomPasswordStrengthValidator
            decorates: 'rollerworks.password_strength_validator'
    
  3. Localization: Customize error messages per locale by overriding the translator or using Symfony’s validation groups:

    new PasswordAssert\ValidPassword([
        'message' => 'Le mot de passe est trop faible.',
        'groups' => ['fr']
    ]);
    

Pro Tips

  • Progressive Strength: Use minStrength with incremental levels (e.g., weakmedium) to guide users toward stronger passwords.
  • A/B Testing: Dynamically switch strength levels between user groups to test security vs. usability tradeoffs.
  • Audit Logs: Log validation failures (without passwords) to monitor common weak patterns:
    if ($errors->count()) {
        $this->logger->warning('Password validation failed', [
            'errors' => $errors->getIterator(),
            'user_id' => $user->id
        ]);
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky