19 November 2026

Razor Pages Form Validation for Beginners: A Student Registration Example

  Asp.Net CS By Example       19 November 2026

A form can look correct while still sending an empty name or an invalid email. In this lesson you will build an ASP.NET Core Razor Page that checks each field and shows a helpful message. This example validates input; it does not save a student to a database yet.

What you will learn

  • Write rules with data annotation attributes.
  • Bind form fields with asp-for and [BindProperty].
  • Check ModelState.IsValid on the server.
  • Show errors and redirect after a successful POST.

Before you start: Try the first Razor Pages student form. The example below uses the standard webapp template.

How validation works

Student fills form → Browser sends POST → Razor Page checks rules → Show errors or success

1. Create a Razor Pages project

dotnet new webapp -n StudentRazorValidation
cd StudentRazorValidation
dotnet run

Stop the app before editing. Add these files to the project. The namespace matches the project name.

2. Describe valid student input

Create Models/StudentInput.cs. Required rejects missing values. StringLength, EmailAddress and Range check the values that were entered. Year is nullable so an empty field does not silently become zero.

using System.ComponentModel.DataAnnotations;

namespace StudentRazorValidation.Models;

public class StudentInput
{
    [Required(ErrorMessage = "Enter your name.")]
    [StringLength(60, MinimumLength = 2)]
    public string Name { get; set; } = string.Empty;

    [Required(ErrorMessage = "Enter your email address.")]
    [EmailAddress(ErrorMessage = "Enter a valid email address.")]
    public string Email { get; set; } = string.Empty;

    [Required(ErrorMessage = "Choose a year from 1 to 5.")]
    [Range(1, 5, ErrorMessage = "Year must be between 1 and 5.")]
    public int? Year { get; set; }
}

3. Check the submitted form

Create Pages/Register.cshtml.cs. BindProperty receives the posted fields. If validation fails, Page() redraws the form with messages. A successful POST redirects, so refreshing the page will not submit the form again.

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using StudentRazorValidation.Models;

namespace StudentRazorValidation.Pages;

public class RegisterModel : PageModel
{
    [BindProperty]
    public StudentInput Input { get; set; } = new();

    public IActionResult OnPost()
    {
        if (!ModelState.IsValid)
        {
            return Page();
        }

        // Validation only. A later lesson saves the student.
        TempData["Notice"] = $"Form accepted for {Input.Name}.";
        return RedirectToPage();
    }
}

4. Show the fields and errors

Create Pages/Register.cshtml. Each validation message is placed beside its field. The optional validation scripts help visitors immediately, while the server-side ModelState check remains essential.

@page
@model StudentRazorValidation.Pages.RegisterModel
@{
    ViewData["Title"] = "Student registration";
}

<h1>Student registration</h1>

@if (TempData["Notice"] is string notice)
{
    <div class="alert alert-success" role="status">@notice</div>
}

<form method="post">
    <div asp-validation-summary="ModelOnly" class="text-danger"></div>
    <div class="mb-3">
        <label asp-for="Input.Name"></label>
        <input asp-for="Input.Name" class="form-control" />
        <span asp-validation-for="Input.Name" class="text-danger"></span>
    </div>
    <div class="mb-3">
        <label asp-for="Input.Email"></label>
        <input asp-for="Input.Email" class="form-control" />
        <span asp-validation-for="Input.Email" class="text-danger"></span>
    </div>
    <div class="mb-3">
        <label asp-for="Input.Year"></label>
        <input asp-for="Input.Year" class="form-control" />
        <span asp-validation-for="Input.Year" class="text-danger"></span>
    </div>
    <button type="submit" class="btn btn-primary">Check form</button>
</form>

@section Scripts {
    <partial name="_ValidationScriptsPartial" />
}

5. Test the result

Run dotnet run and open /Register on the local address.

  1. Submit every field empty: each field should show an error.
  2. Enter a one-letter name: the minimum length rule should fail.
  3. Enter an email without @ and year 8: both should fail.
  4. Enter Asha Patil, asha@example.com and year 2: the page should redirect and show a success notice.

Important: This lesson checks the form but does not store a record. Do not tell visitors that registration is complete until data has actually been saved. Keep the server-side ModelState check even when browser validation works.

Practice task

Add a Course field that requires at least three characters. Test an empty value, a two-character value and a valid value. Which file contains the rule, and which file displays the message?

Next: Save validated student data with EF Core and SQLite. Read the official Razor Pages validation guide for more detail.

logoblog

Thanks for reading Razor Pages Form Validation for Beginners: A Student Registration Example

Previous
« Prev Post

No comments:

Post a Comment

Please do not enter any spam link in the comment box.