passwordStrength static method

String? Function(String?) passwordStrength({
  1. int minLength = 8,
  2. bool requireUppercase = true,
  3. bool requireLowercase = true,
  4. bool requireDigit = true,
  5. bool requireSpecial = false,
  6. String? message,
})

Password strength

Implementation

static String? Function(String?) passwordStrength({
  int minLength = 8,
  bool requireUppercase = true,
  bool requireLowercase = true,
  bool requireDigit = true,
  bool requireSpecial = false,
  String? message,
}) {
  return (value) {
    if (value == null || value.isEmpty) return null;

    final errors = <String>[];

    if (value.length < minLength) {
      errors.add('at least $minLength characters');
    }
    if (requireUppercase && !value.contains(RegExp(r'[A-Z]'))) {
      errors.add('an uppercase letter');
    }
    if (requireLowercase && !value.contains(RegExp(r'[a-z]'))) {
      errors.add('a lowercase letter');
    }
    if (requireDigit && !value.contains(RegExp(r'[0-9]'))) {
      errors.add('a number');
    }
    if (requireSpecial && !value.contains(RegExp(r'[!@#$%^&*(),.?":{}|<>]'))) {
      errors.add('a special character');
    }

    if (errors.isNotEmpty) {
      return message ?? 'Password must contain ${errors.join(', ')}';
    }
    return null;
  };
}