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.

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.

    6 thoughts on “Data annotations object graph validation is coming to Blazor

    • January 28, 2020 at 1:03 pm
      Permalink

      Will this make production any time soon, do you know?

    • January 28, 2020 at 1:09 pm
      Permalink

      I have no idea how soon it will happen. Next milestone for Blazor is May, this year. Hopefully they will get validation or even somekind of MVVM ready.

    • March 7, 2020 at 12:13 am
      Permalink

      How does this work for repeating controls?
      For instance, if your name, email, and text were in a control and repeated on the page several times.

    • April 3, 2020 at 9:06 am
      Permalink

      Will this work with child components too? My child components actually validate, but don’t display the error message.

    • April 4, 2020 at 9:29 am
      Permalink

      I remember some news after writing this post that validation will work over child component trees too. I have not checked yet if and how it works with latest Blazor code. Based on what you wrote it seems to me that there have been some progress and the question is what do you need to change in your code to make child components display error messages.

    • June 23, 2021 at 8:38 am
      Permalink

      Why the ‘ObjectGraphDataAnnotationsValidator ‘ solution is Blazor only? I would like it if Microsoft Teams would talk togehter. A web-api-project would benefit from this feature too.

    Leave a Reply

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