How can I create strong passwords with FluentValidation?

Viewed 1448

I am designing a user registration screen using FluentValidation.

I want to establish a control mechanism that will provide information on all steps as follows.

The code I tried;

RuleFor(p => p.Password).Matches(@"[A-Z]+").WithMessage("Your password must contain at least one uppercase letter.");
        RuleFor(p => p.Password).Matches(@"[a-z]+").WithMessage("Your password must contain at least one lowercase letter.");
        RuleFor(p => p.Password).Matches(@"[0-9]+").WithMessage("Your password must contain at least one number.");
        RuleFor(x => x.Password).Matches(@"[\!\?\*\.]*$").WithMessage("Your password must contain at least one (!? *.).");

But I could not reach the result I wanted. I also looked at the FluentValidation documentation but could not see any useful example.

I would be glad if you help.

Thank you.

1 Answers

Please refer to the following example:

public class Login
    { 
        public string Password { get; set; }
    }


     public class PassWordValidator : AbstractValidator<Login>
        {
            public PassWordValidator()
            {
                RuleFor(p => p.Password).NotEmpty().WithMessage("Your password cannot be empty")
                    .MinimumLength(8).WithMessage("Your password length must be at least 8.")
                    .MaximumLength(16).WithMessage("Your password length must not exceed 16.")
                    .Matches(@"[A-Z]+").WithMessage("Your password must contain at least one uppercase letter.")
                    .Matches(@"[a-z]+").WithMessage("Your password must contain at least one lowercase letter.")
                    .Matches(@"[0-9]+").WithMessage("Your password must contain at least one number.")
                    .Matches(@"[\!\?\*\.]+").WithMessage("Your password must contain at least one (!? *.).");
            }
        }

Action:

 [HttpPost]
        public IActionResult TestPassword(Login model)
        {
            PassWordValidator _validator = new PassWordValidator();
            var validResult = _validator.Validate(model);
            if (!validResult.IsValid)
            {
                return BadRequest(validResult.Errors);
            }
            return Ok();
        }

Here is the test result by postman:

enter image description here

Related