Loading, please wait...

A to Z Full Forms and Acronyms

How do you validate forms in Blazor?

This code will help you to understand how to validate forms in Blazor.

The form validation in Blazor is achieved using data annotations. The following two tags are used for validations and display the validation error message:

  • <DataAnnotationsValidator />
  • <ValidationSummary />

Refer to the following code example for simple form validation in Blazor.

[Person.cs]

using System.ComponentModel.DataAnnotations;
public class Person
    {
        [Required]
        [StringLength(15, ErrorMessage = "{0} length must be between {2} and {1}.", MinimumLength = 6)]
        public string FirstName { get; set; }

        [Required]
        [DataType(DataType.Password)]
        [StringLength(15, ErrorMessage = "{0} length must be between {2} and {1}.", MinimumLength = 6)]
        public string LastName { get; set; }

        [Required]
        [Range(1, 100, ErrorMessage = "Age should a number between (1-100).")]
        public int Age { get; set; }
    }

[FormValidation.razor]

<EditForm Model="@person" OnValidSubmit="@HandleValidSubmit">
   <DataAnnotationsValidator />
   <ValidationSummary />
    <label for="firstname">First Name: </label>
    <InputText Id="firstname" @bind-Value="@person.FirstName"></InputText>

    <label for="lastname">Last Name: </label>
    <InputText Id="lastname" @bind-Value="@person.LastName"></InputText>

    <label for="age">Age: </label><br />
    <InputNumber Id="age" @bind-Value="@person.Age"></InputNumber>

    <button type="submit">Submit</button>
</EditForm>
@code {
    private Person person = new Person();
    private void HandleValidSubmit()
    {
        Console.WriteLine("OnValidSubmit");
    }
}
A to Z Full Forms and Acronyms

Related Article