Lesson 7 of 10
Forms and Data Validation
Build an EditForm, validate models with data annotations, and display useful validation messages.
Most business applications need forms. Blazor provides EditForm and built-in input components that work with model validation.
1. Create the model
Create a folder named Models, then add Student.cs:
using System.ComponentModel.DataAnnotations;
namespace BlazorTutorialApp.Models;
public class Student
{
[Required(ErrorMessage = "Name is required.")]
[StringLength(60, MinimumLength = 2)]
public string Name { get; set; } = "";
[Required(ErrorMessage = "Email is required.")]
[EmailAddress(ErrorMessage = "Enter a valid email address.")]
public string Email { get; set; } = "";
[Required]
public string Course { get; set; } = "";
[Range(1, 6)]
public int Year { get; set; } = 1;
}
2. Create StudentForm.razor
@page "/student-form"
@using BlazorTutorialApp.Models
<h1>Student Form</h1>
<EditForm Model="@student" OnValidSubmit="SaveStudent">
<DataAnnotationsValidator />
<ValidationSummary />
<div class="mb-3">
<label>Name</label>
<InputText class="form-control" @bind-Value="student.Name" />
<ValidationMessage For="@(() => student.Name)" />
</div>
<div class="mb-3">
<label>Email</label>
<InputText class="form-control" @bind-Value="student.Email" />
<ValidationMessage For="@(() => student.Email)" />
</div>
<div class="mb-3">
<label>Course</label>
<InputText class="form-control" @bind-Value="student.Course" />
</div>
<div class="mb-3">
<label>Year</label>
<InputNumber class="form-control" @bind-Value="student.Year" />
</div>
<button class="btn btn-primary" type="submit">Save</button>
</EditForm>
<p>@message</p>
@code {
private Student student = new();
private string message = "";
private void SaveStudent()
{
message = $"Saved {student.Name} successfully.";
}
}
3. What validation does
DataAnnotationsValidator connects the form to attributes such as [Required], [StringLength], and [Range]. OnValidSubmit runs only after the model passes validation.
Try it yourself
Add a required Phone property to Student and display a validation message for it.