Blazor validate unmodified form

I want to validate a Blazor form even though the user hasn’t changed the value of any form fields. (By default, Blazor only validates fields after they are modified.)

How can I validate the form without requiring user interaction (editing a field, clicking a button, etc.)? I want to validate the form when it initially shows.

Here is my code:

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

<EditForm Model="@formModel" Context="currentEditContext">
    <DataAnnotationsValidator />

    <p>
        <label>My Text: <InputText @bind-Value="formModel.Text" /></label>
        <ValidationMessage For="@(() => formModel.Text)" />
    </p>

    <p>Form valid: @currentEditContext.Validate()</p>
</EditForm>

@code
{
    FormModel formModel = new();

    private class FormModel
    {
        [Required]
        public string Text { get; set; } = "";
    }
}

I tried using various methods on my EditContext object, but none of them triggered validation.
  • editContext.Validate();
  • editContext.NotifyValidationStateChanged();
  • editContext.NotifyFieldChanged(editContext.Field("Text"));

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

I discovered that I can trigger the form validation by running editContext.Validate() inside OnAfterRender().

This code validates the form immediately upon loading the page:

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

<EditForm EditContext="editContext">
    <DataAnnotationsValidator />

    <p>
        <label>My Text: <InputText @bind-Value="formModel.Text" /></label>
        <ValidationMessage For="@(() => formModel.Text)" />
    </p>

    <p>Form valid: @(!editContext.GetValidationMessages().Any())</p>
</EditForm>

@code
{
    FormModel formModel = new();
    EditContext editContext;

    private class FormModel
    {
        [Required]
        public string Text { get; set; } = "";
    }

    protected override void OnInitialized()
    {
        editContext = new(formModel);
        base.OnInitialized();
    }

    protected override void OnAfterRender(bool firstRender)
    {
        if (firstRender)
        {
            editContext.Validate();
            StateHasChanged(); // Update the "Form valid" message
        }

        base.OnAfterRender(firstRender);
    }
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x