Lesson 3
Validating Data in Razor Pages
Introduction

Welcome to the lesson on "Validating Data in Razor Pages." In this lesson, we will focus on the importance of data validation in web applications and how to implement it using Razor Pages in ASP.NET Core.

Previously, you learned the basics of binding data in Razor Pages and applied simple validation rules using attributes like [Required]. This lesson will build on that knowledge by diving deeper into setting up and handling validation for user inputs. Our goal is to ensure that the data entering your application is consistent, correct, and usable.

Let's start by examining the starter code provided. This code sets up a basic ASP.NET Core Razor Pages project with a registration form that accepts an email address. We'll use this form to demonstrate how to implement and handle data validation.

Understanding Data Annotations for Validation

Data annotations are attributes you can apply to model properties to enforce validation rules. Some common validation attributes include [Required], [EmailAddress], and [StringLength]. These annotations help you ensure that the data users submit meets certain criteria before processing it in your application.

  • [Required]: Ensures that a field is not empty.
  • [EmailAddress]: Validates that a field contains a valid email address format.
  • [StringLength(maximumLength)]: Specifies the maximum length of a string property.

When you annotate your model properties with these attributes, ASP.NET Core automatically performs validation checks against them when the form is submitted.

Implementing Validation in Razor Pages

To illustrate how to implement validation, let's use the Email field in the registration form. In the Register.cshtml file you can notice how the form uses the asp-for and asp-validation-for tags.

Register.cshtml:

HTML, XML
1@page 2@model RegisterModel 3<form method="post"> 4 <label asp-for="Email"></label> 5 <input asp-for="Email" name="Email" /> 6 <span asp-validation-for="Email" class="text-danger"></span> 7 <button type="submit">Register</button> 8</form> 9 10@if (Model.RegistrationSuccessful) 11{ 12 <p>Registration successful! Your email: @Model.Email</p> 13} 14else if (Model.RegistrationAttempted && !Model.RegistrationSuccessful) 15{ 16 <p class="text-danger">Registration failed. Please correct the errors and try again.</p> 17}

The asp-for tag helper automatically binds the input element to the Email property in your model, and the asp-validation-for tag displays validation errors for that property.

Handling Validation in the Code-Behind

Next, let's look at how to handle validation in the code-behind file of the Razor Page. Let's look at the RegisterModel class:

C#
1public IActionResult OnPost() 2{ 3 RegistrationAttempted = true; 4 5 if (!ModelState.IsValid) 6 { 7 RegistrationSuccessful = false; 8 return Page(); 9 } 10 11 // Registration logic - For testing purposes, we'll assume registration is always successful 12 RegistrationSuccessful = true; 13 return Page(); 14}

In the OnPost method, we check if the ModelState is valid. If it is not valid (i.e., there are validation errors), we set RegistrationSuccessful to false and return the Page, allowing the user to correct their input.

Displaying Validation Errors in the UI

When validation errors are present, they need to be communicated to the user effectively. This is where the asp-validation-for tag comes in handy. It automatically displays error messages next to the input fields that failed validation.

We've already seen individual validation messages in the Register.cshtml file:

HTML, XML
1<span asp-validation-for="Email" class="text-danger"></span>

This tag will display validation errors related to the Email property in a red text format.

Adding Additional Validation Rules

To further demonstrate how versatile validation in Razor Pages can be, let's add an additional validation rule for password complexity to our registration form.

First, update the RegisterModel in Register.cshtml.cs:

C#
1public class RegisterModel : PageModel 2{ 3 [BindProperty] 4 [Required] 5 [EmailAddress] 6 public string Email { get; set; } 7 8 [BindProperty] 9 [Required] 10 [StringLength(100, MinimumLength = 6, ErrorMessage = "Password must be between 6 and 100 characters.")] 11 public string Password { get; set; } 12 13 public bool RegistrationSuccessful { get; set; } 14 public bool RegistrationAttempted { get; set; } 15 16 public void OnGet() 17 { 18 // Set both flags to `false` on page open, we'll set them to `true` after the form is submitted and if it passes validation 19 RegistrationSuccessful = false; 20 RegistrationAttempted = false; 21 } 22 23 public IActionResult OnPost() 24 { 25 RegistrationAttempted = true; 26 27 if (!ModelState.IsValid) 28 { 29 RegistrationSuccessful = false; 30 return Page(); 31 } 32 33 // Registration logic - For testing purposes, we'll assume registration is always successful 34 RegistrationSuccessful = true; 35 return Page(); 36 } 37}

Then, update Register.cshtml to include a password field:

HTML, XML
1<form method="post"> 2 <label asp-for="Email"></label> 3 <input asp-for="Email" name="Model.Email" /> 4 <span asp-validation-for="Email" class="text-danger"></span> 5 6 <label asp-for="Password"></label> 7 <input asp-for="Password" type="password" name="Model.Password" /> 8 <span asp-validation-for="Password" class="text-danger"></span> 9 10 <button type="submit">Register</button> 11</form>

Now, the form includes a password field that requires the password to be between 6 and 100 characters. If the validation rules are violated, the appropriate error message will be displayed next to the input.

Lesson Summary

In this lesson, you learned the importance of validating data in Razor Pages applications. We covered:

  • An overview of common data annotations and how they work
  • How to set up validation in the .cshtml file
  • How to handle validation in the code-behind and check if ModelState is valid
  • Displaying validation errors in the UI
  • Adding additional validation rules to your model and Razor Pages

Congratulations on successfully completing this lesson and the course! Data validation is crucial in ensuring that the data entering your application is correct and reliable.

Keep practicing by adding more validation rules and exploring custom validation attributes to deepen your understanding and improve your web applications. Happy coding!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.