Ask Your Question
3

How to implement validation on a complex model form in Blazor containing a list property using FluentValidation?

asked 2023-06-03 21:24:15 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-06-03 21:39:01 +0000

bukephalos gravatar image

FluentValidation is a popular library for adding validation to models in .NET. In this guide, we will see how to use this library to implement validation on a complex model form in Blazor that contains a list property.

Step 1: Install FluentValidation

First, we need to install FluentValidation into our Blazor project. We can do this by running the following command in the Package Manager Console:

Install-Package FluentValidation

Step 2: Create a Model

Next, we create a model that we want to validate. In this example, we have a model containing a string property and a list of another model.

public class MyModel
{
    public string Name { get; set; }
    public List<ChildModel> Children { get; set; }
}

public class ChildModel
{
    public string Name { get; set; }
    public int Age { get; set; }
}

Step 3: Create a Validator

Now, we create a validator for our model using FluentValidation. We can add rules for each property that we want to validate.

public class MyModelValidator : AbstractValidator<MyModel>
{
    public MyModelValidator()
    {
        RuleFor(x => x.Name).NotEmpty().WithMessage("Name is required.");
        RuleForEach(x => x.Children).SetValidator(new ChildModelValidator());
    }
}

public class ChildModelValidator : AbstractValidator<ChildModel>
{
    public ChildModelValidator()
    {
        RuleFor(x => x.Name).NotEmpty().WithMessage("Child name is required.");
        RuleFor(x => x.Age).GreaterThan(0).WithMessage("Age must be greater than 0.");
    }
}

In this example, we have added rules to ensure that the Name property of our MyModel is not empty, and for each ChildModel in the Children list, we have added rules to ensure that Name is not empty and Age is greater than 0.

Step 4: Use the Validator in Blazor

Finally, we can use our validator in our Blazor form to validate user input. We can inject our validator into our component and add it to our EditForm as a validation provider.

@using FluentValidation
@using FluentValidation.Results

@inject MyModelValidator Validator

<EditForm Model="@Model" OnValidSubmit="@HandleValidSubmit">
    <DataAnnotationsValidator />
    <ValidationSummary />

    <InputText @bind-Value="@Model.Name" />

    @foreach (var childModel in Model.Children)
    {
        <InputText @bind-Value="@childModel.Name" />
        <InputNumber @bind-Value="@childModel.Age" />
    }

    <button type="submit">Save</button>
</EditForm>

@code {
    MyModel Model = new MyModel()
    {
        Children = new List<ChildModel>()
    };

    async Task HandleValidSubmit()
    {
        ValidationResult validationResult = Validator.Validate(Model);
        if (validationResult.IsValid)
        {
            // Submit the form
        }
    }
}

In this example, we have added the DataAnnotationsValidator and ValidationSummary components to our form to display validation errors to the user. We have also added an OnValidSubmit event to our EditForm and called our validator's Validate method during submission. If the form is valid, we can submit it. If there are errors, validation messages will be displayed to the user.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-03 21:24:15 +0000

Seen: 12 times

Last updated: Jun 03 '23