Data annotations object graph validation is coming to Blazor

Future versions of Blazor will support cascading data annotations support meaning that validation of child components is also supported. First experimental bits were released counted hours ago with .NET Core 3.1 Preview 2. Here’s how object graph validation will work in Blazor.

Building object graph

My previous post about Blazor form validation introduced how validation is implemented for EditForm element used on Blazor pages. The post started with simple GuestbookEntry class. For this post I will use a little bit different guestbook entry and this one has child component.

public class GuestbookEntry
{
    [Required]
    public Author Author { get; set; }

    [Required]
    public string Text { get; set; }

    public GuestbookEntry()
    {
        Author = new Author();
    }
}

public class Author
{
    [Required]
    public string Name { get; set; }

    [EmailAddress]
    public string Email { get; set; }
}

I skip page markup for a moment to show that validation doesn’t work for properties of child component.

Blazor form validation with data annotations validator

Data annotations validation doesn’t support child components out-of-box and this is why name and e-mail fields were not validated.

Introducing experimental object graph validation

.NET Core 3.1 Preview 2 introduces experimental support for object graph validation using data annotations. There’s new form validator called ObjectGraphDataAnnotationsValidator and currently it comes with additional Nuget package:

  • Microsoft.AspNetCore.Blazor.DataAnnotations.Validation

We need also one modification to GuestbookEntry class – adding ValidateComplexType attribute to Author property. Without this attribute the validation works only when user leaves the field but not when whole model is validated.

public class GuestbookEntry
{
    [Required]
[ValidateComplexType]
    public Author Author { get; set; }

    [Required]
    public string Text { get; set; }

    public GuestbookEntry()
    {
        Author = new Author();
    }
}

On page we must replace DataAnnotationsValidator with new ObjectGraphDataAnnotationsValidator.

@page "/"
@using BlazorApp6.Models

<h1>My guestbook</h1>

<p>Leave me a message if you like my site</p>

<EditForm Model="@Model" OnValidSubmit="@HandleValidSubmit" OnInvalidSubmit="@HandleInvalidSubmit">
    <div class="alert @StatusClass">@StatusMessage</div>

    <ObjectGraphDataAnnotationsValidator />
    <ValidationSummary />

    <div class="form-group">
        <label for="name">Name: </label>
        <InputText Id="name" Class="form-control" @bind-Value="@Model.Author.Name"></InputText>
        <ValidationMessage For="@(() => Model.Author.Name)" />
    </div>
    <div class="form-group">
        <label for="name">E-mail: </label>
        <InputText Id="name" Class="form-control" @bind-Value="@Model.Author.Email"></InputText>
        <ValidationMessage For="@(() => Model.Author.Email)" />
    </div>
    <div class="form-group">
        <label for="body">Text: </label>
        <InputTextArea Id="body" Class="form-control" @bind-Value="@Model.Text"></InputTextArea>
        <ValidationMessage For="@(() => Model.Text)" />
    </div>
    <button type="submit">Ok</button>

</EditForm>

@code
{
    private string StatusMessage;
    private string StatusClass;

    private GuestbookEntry Model = new GuestbookEntry();

    protected void HandleValidSubmit()
    {
        StatusClass = "alert-info";
        StatusMessage = DateTime.Now + " Handle valid submit";
    }

    protected void HandleInvalidSubmit()
    {
        StatusClass = "alert-danger";
        StatusMessage = DateTime.Now + " Handle invalid submit";
    }
}

After these changes Blazor will validate also properties of Author component like shown on the following screenshot.

Blazor form validation with data annotations object graph validator

As a result validation of our not so primitive view model works perfectly.

NB! There’s also FluentValidation support available for Blazor by Chris Sainty. FluentValidation is powerful and popular validation library. Those familiar with it can use it also in Blazor like they use it in other applications.

Wrapping up

Blazor is making step-by-step its way to be serious application development platform and it’s good to see that product team is working hard on validation too. There are more new validators under construction. Data annotations are popular in .NET world and now Blazor supports also validation of whole object graphs. Although object graph validation is still experimental it’s worth to try it out.

Liked this post? Empower your friends by sharing it!

Gunnar Peipman

Gunnar Peipman is ASP.NET, Azure and SharePoint fan, Estonian Microsoft user group leader, blogger, conference speaker, teacher, and tech maniac. Since 2008 he is Microsoft MVP specialized on ASP.NET.

    Leave a Reply

    Your email address will not be published. Required fields are marked *