skip to Main Content

I have the following class

public class User 
{
  string firstName;
  string lastName;
}

And for that one I want to use a regex with fluent validation to be accepted just letters and whitespaces. As a regex might be a good example but I didn’t find any implementation

And I created the following validator

    public class UserValidator:AbstractValidator<User>
{
    public UserValidator()
    {
        RuleFor(x => x.Id)
            .NotEmpty()
            .NotNull();
        RuleFor(x => x.Name)
            .NotEmpty().WithMessage("Please ensure that to set a value for {PropertyName}")
            .Must(BeValidName).WithMessage("Please ensure that to set a valid value for {PropertyName}")
            .Length(3, 30);

        private bool BeValidName(string name)
    {
        return name.All(Char.IsLetter);
    }

}

But I m going to search something better 😀 Do you guys have any idea ? Thanks!

2

Answers


  1. You can use regex validators

    RuleFor(x => x.Name).Matches("some regex here");
    
    Login or Signup to reply.
  2. This is an example of accepting only letters and spaces for the Name field using FluentValidation and Regex.

    public class User
    {
        public string Id;
        public string Name;
    }
    
    public class UserValidator : AbstractValidator<User>
    {
        public UserValidator()
        {
            RuleFor(x => x.Id)
                .NotEmpty()
                .NotNull();
            RuleFor(x => x.Name)
                .NotEmpty()
                .Matches(@"^[A-Za-zs]*$").WithMessage("'{PropertyName}' should only contain letters.")
                .Length(3, 30);
        }
    }
    

    Validation Output:

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search