FluentValidation
Reuse the AbstractValidator<T> your application already has. UseFluentValidation(),
from the separate Bit.Borm.FluentValidation package, runs it against the bound model and puts each
failure on the field its property path names - Address.City, Lines[0].Product - cross-field
rules included. Every rule on this form comes from the validator below; the schema adds none of its own.
Submit the empty form to see the validator's messages under their fields. Then enter 5 or more years of experience
and a short motivation: the motivation rule only applies to senior candidates (
.When(x => x.YearsExperience >= 5)),
so it appears only then - and goes again once the text is long enough.
View source
@page "/fluent-validation"
@inject IValidator<JobApplication> Validator @* registered in Program.cs *@
<BormView State="_state" OnValidSubmit="HandleSubmit" SubmitText="Apply" />
@code {
private readonly JobApplication _model = new();
private BormState _state = default!;
protected override void OnInitialized()
{
var schema = BormBuilder.For<JobApplication>()
.Title("Job application")
.Field(x => x.FirstName, f => f.Label("First name"))
.Field(x => x.LastName, f => f.Label("Last name"))
.Field(x => x.Email)
.Field(x => x.YearsExperience, f => f.Label("Years of experience"))
.Field(x => x.DesiredSalary, f => f.Label("Desired salary"))
.Field(x => x.Motivation, f => f.AsTextArea(4).Label("Why do you want this role?"))
.Build();
// Validation comes entirely from the FluentValidation validator. With validators registered
// in DI, .UseFluentValidation() with no argument resolves IValidator<JobApplication> itself.
_state = new BormState(schema, new BormModelDataAccessor(_model))
.UseFluentValidation(Validator);
}
public void Dispose() => _state.Dispose();
}
// Forms/JobApplicationValidator.cs - an ordinary FluentValidation validator, unaware of Borm.
public class JobApplicationValidator : AbstractValidator<JobApplication>
{
public JobApplicationValidator()
{
RuleFor(x => x.FirstName).NotEmpty().MaximumLength(40);
RuleFor(x => x.LastName).NotEmpty().MaximumLength(40);
RuleFor(x => x.Email).NotEmpty().EmailAddress();
RuleFor(x => x.YearsExperience).InclusiveBetween(0, 60);
RuleFor(x => x.DesiredSalary)
.GreaterThan(0)
.LessThanOrEqualTo(500_000).WithMessage("Let's keep it realistic (≤ 500,000).");
// Cross-field rule: senior candidates must explain their motivation.
RuleFor(x => x.Motivation)
.NotEmpty()
.MinimumLength(20)
.When(x => x.YearsExperience >= 5)
.WithMessage("Candidates with 5+ years should write at least 20 characters.");
}
}
// Program.cs
builder.Services.AddScoped<IValidator<JobApplication>, JobApplicationValidator>();Worth knowing
- Two ways to hand it the validator. Pass one, as this page does, or register validators in DI and
call
state.UseFluentValidation()with no argument: theIValidator<TModel>for the bound model is resolved from the state's service provider.throwIfMissing: truecatches a forgotten registration during development. - Hidden fields are left alone. A validator sees the whole model and knows nothing about the form's conditions, so a failure on a field the schema is currently hiding is dropped - otherwise a rule on an abandoned branch would refuse the submit and point at a control that is not on the page.
- It composes.
UseFluentValidation(),UseDataAnnotations()and the schema's own rules all run, and a complaint two layers word identically is read once - see DataAnnotations & IValidatableObject.BormExternalValidator.CombineWith(...)does the same for a hand-written external validator.
dotnet add package Bit.Borm.FluentValidation