Search code examples
validationblazor

Blazor: How can I display validation messages when a form is displayed


I'm using .NET 5 with Blazor Server Side

I want any validation error messages to be displayed when the form is first displayed (without having to submit the form or modify the fields). From what I read, it seemed that calling context.Validate() would do the trick but, alas, no.

Here's a paired-down page to illustrate the issue.

@page "/studentedit"
@using System.ComponentModel.DataAnnotations

<EditForm EditContext="@context">
    <DataAnnotationsValidator />

    <InputText @bind-Value="@student.FirstName"></InputText>
    <ValidationMessage For="@(() => student.FirstName)" />

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

@code {
    private Student student = new Student();
    private EditContext context;

    protected override async Task OnInitializedAsync()
    {
        context = new EditContext(student);
        context.Validate(); // <--- I thought this would work
        await base.OnInitializedAsync();
    }

    public class Student
    {
        [Required(ErrorMessage = "First Name is required")]
        public string FirstName { get; set; }
    }
}

Solution

  • On OnInitialized the ValidationMessage component is not instantiated yet and thus can not display any validation errors.

    Calling EditContext.Validate in OnAfterRender works.

    @page "/studentedit"
    @using System.ComponentModel.DataAnnotations
    
    <EditForm EditContext="@context">
        <DataAnnotationsValidator />
    
        <InputText @bind-Value="@student.FirstName"></InputText>
        <ValidationMessage For="@(() => student.FirstName)" />
    
        <button type="submit">Submit</button>
    </EditForm>
    
    @code {
        private Student student = new Student();
        private EditContext context;
    
        protected override void OnInitialized()
        {
            context = new EditContext(student);
            base.OnInitializedAsync();
        }
    
        protected override void OnAfterRender(bool firstRender)
        {
            if (firstRender)
                context.Validate();
        }
    
        public class Student
        {
            [Required(ErrorMessage = "First Name is required")]
            public string FirstName { get; set; }
        }
    }