If you want to check for Min Length only:
RuleFor(x => x.Name).NotEmpty().WithMessage("Name required")
.Length(10)
.WithMessage("Name should have at least 10 chars.");
If you want to check for Max Length only:
RuleFor(x => x.Name).NotEmpty().WithMessage("Name required")
.Length(0, 15)
.WithMessage("Name should have 15 chars at most.");
This is the API documentation for the second one (public static IRuleBuilderOptions<T, string> Length<T>(this IRuleBuilder<T, string> ruleBuilder, int min, int max)
):
Summary: Defines a length validator on the current rule builder, but only for string properties. Validation will fail if the length of the string is outside of the specifed range. The range is inclusive.
Parameters:
ruleBuilder: The rule builder on which the validator should be defined
min:
max:
Type parameters:
T: Type of object being validated
You could also create an extension like this (using Must
instead of Length
):
using FluentValidation;
namespace MyProject.FluentValidationExtensiones
{
public static class Extensiones
{
public static IRuleBuilderOptions<T, string> MaxLength<T>(this IRuleBuilder<T, string> ruleBuilder, int maxLength)
{
return ruleBuilder.Must(x => string.IsNullOrEmpty(x) || x.Length <= maxLength);
}
}
}
And use it like this:
RuleFor(x => x.Name).NotEmpty().WithMessage("Name required")
.MaxLength(15)
.WithMessage("Name should have 15 chars at most.");