FluentValidation is a popular validation library for.NET Core. It provides advantages over the DataAnnotations
validation system integrated into.NET Core, such as an enormous collection of rules, more straightforward configuration, and flexibility.
Blazor includes built-in support for forms and validation, but Blazor is unaware of FluentValidation
.This blog post will show you how to add fluent validation to the blazor application.
First, install the two NuGet packages in your application.
dotnet add package FluentValidation
dotnet add package Blazored.FluentValidation
We’re also going to need something to validate, so let’s create a simple User
class. This will define the various fields that will be available on the form.
public class User{
public string UserName{get;set;}
public string Password {get;set;}
}
The second step is to create a separate class, UserValidator and inherit it from the AbstractValidator
class that FluentValidator provides.
public class UserValidator:AbstractValidator<User>
{
public UserValidator()
{
RuleFor(user => user.UserName).NotEmpty().WithMessage("UserName is required");
RuleFor(user => user.Password).NotEmpty().WithMessage("Password is required");
}
}
As you can see that I am adding a rule for user classes like UserName and Password cannot be empty.
Go to your razor component and add the FluentValidationValidator
component inside the edit form class. That’s it; now, your form is protected from fluent validations.
@using Blazored.FluentValidation
<EditForm Model="@userModel" OnValidSubmit="@HandleValidSubmit">
<FluentValidationValidator/>
<label>UserName</label>
<InputText id="username" @bind-Value="userModel.UserName" />
<ValidationMessage For="@(()=>userModel.UserName)"/>
<label>Password</label>
<InputText id="password" @bind-Value="userModel.Password" />
<ValidationMessage For="@(()=>userModel.Password)"/>
<br>
<span>@message</span>
<button type="submit" >Submit</button>
</EditForm>
@code {
private User userModel = new();
private string message="";
protected override void OnInitialized() {
}
private void HandleValidSubmit() {
message="Form Submit";
}
}