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
You can use regex validators
This is an example of accepting only letters and spaces for the
Name
field using FluentValidation and Regex.Validation Output: