How To Add Form Validation In Blazor Application

This blog post will show you how to add validation in blazor form.
Before implementing the validation, you must get familiar with the most important component of blazor validation, EditContext and EditForm.
As per the MSDN

EditContext Holds metadata related to a data editing process, such as flags to indicate which fields have been modified and the current set of validation messages.

EditForm Renders a form element that cascades an EditContext to descendants.

Validation Using DataAnotation

Microsoft provides out of the box validation in the blazor application.

Let’s consider you have the following model in your blazor application.

public class User{
    public string UserName{get;set;}
    public string Password {get;set;}

}

and the following form to save the user info

<EditForm Model="@userModel">
    <label>UserName</label>
    <InputText id="username" @bind-Value="userModel.UserName" />
    <label>Password</label>
    <InputText id="password" @bind-Value="userModel.Password" />
    <br>
    <span>@message</span>
    <button type="submit">Submit</button>
</EditForm>

To add validation, we need to do the following things.

  • Add Data Annotation to the model properties
  • Add OnValidSubmit="@HandleValidSubmit", an event to the edit form
  • Add the DataAnnotationsValidator component to the form
  • And Finally, ValidationSummary to the form

After making the above changes, our model and form look below.

   public class User{
    [Required]
    public string UserName{get;set;}
    [Required]
    public string Password {get;set;}

}
<EditForm Model="@userModel" OnValidSubmit="@HandleValidSubmit">
    <DataAnnotationsValidator />
    <ValidationSummary/>
    <InputText id="username" @bind-Value="userModel.UserName" />
    <InputText id="password" @bind-Value="userModel.Password" />
   <br>
    <button type="submit" class="btn btn-success" disabled="@formInvalid">Submit</button>
</EditForm>

If you run the application, you will see the output below.

Show Validation Message Below the Control

If you don’t want to show all the validation messages on the top, you can control it using Microsoft's component. Let’s remove the validation summary component and add the validation message component.

<EditForm Model="@userModel" OnValidSubmit="@HandleValidSubmit">
    <DataAnnotationsValidator />
    <InputText id="username" @bind-Value="userModel.UserName" />
    <ValidationMessage For="@(()=>userModel.UserName)"/>
    <InputText id="password" @bind-Value="userModel.Password" />
    <ValidationMessage For="@(()=>userModel.Password)"/>
    <br>
    <span>@message</span>
    <button type="submit">Submit</button>
</EditForm>

Enable the submit button based on form validation

To enable and disable the submit button based on form validation, the following example:

  • When the component is initialised, it uses the form’s EditContext to assign the model.
  • Enables and disables the submit button in the context OnFieldChanged callback by validating the form.
    The ‘Dispose of’ method implements IDisposable and unsubscribes the event handler. For more information, go here.

Let’s make the changes and see how the code looks like

<EditForm  EditContext="@editContext" OnValidSubmit="@HandleValidSubmit">
    <DataAnnotationsValidator />
    <label>UserName</label>
    <InputText id="username" @bind-Value="userModel.UserName" />
    <ValidationMessage For="@(()=>userModel.UserName)"/>
    <label>Password</label>
    <InputText id="password" @bind-Value="userModel.Password" />
    <ValidationMessage For="@(()=>userModel.Password)"/>
    <br>
    <span>@message</span>
    <button type="submit"  disabled="@formInvalid">Submit</button>
</EditForm>
@code {
    private bool formInvalid = false;
    private EditContext ? editContext;
    private User userModel = new();
    private string message=string.Empty;
    protected override void OnInitialized() {
        editContext = new(userModel);
        editContext.OnFieldChanged += HandleFieldChanged;
    }

    private void HandleFieldChanged(object ? sender, FieldChangedEventArgs e) {
    if (editContext is not null) {
        formInvalid = !editContext.Validate();
      
        StateHasChanged();
    }
    }
    private void HandleValidSubmit() {
 message="Form Submit";
    }
       public void Dispose() { if (editContext is not null) { editContext.OnFieldChanged -= HandleFieldChanged; } }
    }

Please do not post any spam link in the comment box😊

Post a Comment (0)
Previous Post Next Post