Lesson 1
Integrating Client-Side Validation in Razor Pages
Introduction

Welcome to this lesson on Integrating Client-Side Validation in Razor Pages. In this lesson, we will explore the importance of validating data on the client-side and learn how to implement it using Razor Pages in ASP.NET Core. Client-side validation ensures that errors are caught early, improving user experience and reducing unnecessary server load.

In this lesson, you'll understand the differences between client-side and server-side validation and how they can complement each other. By the end of this lesson, you'll be proficient in integrating client-side validation into your Razor Pages applications.

Creating the Validation Model

Let's start by defining model properties with validation annotations. Validation annotations ensure that data meets specified criteria. In this lesson, we are using two common annotations: [Required] and [EmailAddress].

C#
1public class ClientValidationFormModel : PageModel 2{ 3 [BindProperty] 4 [Required(ErrorMessage = "Name is required.")] 5 public string Name { get; set; } 6 7 [BindProperty] 8 [Required(ErrorMessage = "Email is required.")] 9 [EmailAddress(ErrorMessage = "Invalid Email Address.")] 10 public string Email { get; set; } 11 12 public IActionResult OnPost() 13 { 14 if (!ModelState.IsValid) 15 { 16 return Page(); 17 } 18 19 // Handle form submission 20 return Page(); 21 } 22}

Here, we've added error messages to the existing annotations. When a user fails to provide a name or an email or provides an invalid email address, these messages will be displayed.

  • [BindProperty]: This attribute binds data from the form to the model properties.
  • [Required]: Ensures that the field is not left empty.
  • [EmailAddress]: Ensures that the input is in a valid email format.
Building the Razor Page with Client-Side Validation

Next, we'll construct the HTML form and integrate validation attributes.

Let's break it down into our HTML form:

HTML, XML
1<form method="post"> 2 <div class="form-group"> 3 <label asp-for="Name" class="control-label"></label> 4 <input asp-for="Name" class="form-control" /> 5 <span asp-validation-for="Name" class="text-danger"></span> 6 </div> 7 <div class="form-group"> 8 <label asp-for="Email" class="control-label"></label> 9 <input asp-for="Email" class="form-control" /> 10 <span asp-validation-for="Email" class="text-danger"></span> 11 </div> 12 <button type="submit" class="btn btn-primary">Submit</button> 13</form>
  • asp-for="Name" and asp-for="Email": These Tag Helpers bind form elements to the model properties.
  • asp-validation-for="Name" and asp-validation-for="Email": These will display validation messages for the bound properties.
Integrating Client-Side Validation Scripts

Client-side validation relies on JavaScript libraries. For Razor Pages, we will include jQuery and jQuery Validate libraries.

_ValidationScriptsPartial.cshtml

HTML, XML
1<!-- This partial view is used to include validation scripts --> 2<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.3/jquery.validate.min.js"></script> 3<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-unobtrusive/3.2.11/jquery.validate.unobtrusive.min.js"></script>

These scripts enable client-side validation automatically for HTML form elements that use validation attributes.

Enabling Unobtrusive Validation

In our ClientValidationForm.cshtml, let's add the following section at the top:

HTML, XML
1@section Scripts { 2 <partial name="_ValidationScriptsPartial" /> 3}

This includes the validation scripts in the Razor page.

Unobtrusive validation is a way to add client-side validation to your forms without cluttering your HTML with JavaScript. It uses special HTML attributes to define validation rules, which jQuery libraries read and enforce.

For example, when you use asp-for and asp-validation-for, they add these special attributes to your form elements. This way, the jQuery libraries can automatically check the rules (like making sure an email is valid) before the form is submitted. This approach keeps your HTML clean and makes the validation easier to manage.

Enabling Tag Helpers

Tag Helpers simplify creating dynamic content in Razor Pages by combining server-side processing with HTML attributes. They enhance readability, reduce errors, and provide IntelliSense support.

In our application, Tag Helpers like asp-for and asp-validation-for are crucial because they bind form elements directly to model properties. This ensures that input data is validated and displayed correctly, making form handling more efficient and less error-prone.

To use Tag Helpers, add this directive in your view:

C#
1@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

This enables built-in Tag Helpers throughout your views, enhancing both productivity and code quality.

Demonstrating Form Validation

To validate our client-side validated form, let's try submitting the form without filling in the fields or with an invalid email:

  • Leave Name and Email empty and click Submit, and you will see the following errors on the preview tab:

    Plain text
    1Name is required. 2Email is required.
  • Enter an invalid email like invalid-email and click Submit, and you will see:

    Plain text
    1Invalid Email Address.

These validations happen on the client side, helping users correct their errors immediately and reducing server load.

Review and Summary

In this lesson, we learned how to integrate client-side validation into Razor Pages applications. Here's a quick recap:

  • We walked through the starter code.
  • Added validation annotations to the model.
  • Constructed an HTML form with validation attributes.
  • Included jQuery validation scripts for client-side validation.
  • Tested the form to see client-side validation in action.

Client-side validation is important for improving user experience and ensuring that data sent to the server meets defined criteria. It complements server-side validation, providing a robust validation system for your applications.

Now, it's your turn to practice these concepts. Complete the exercises provided to reinforce what you've learned and prepare for future lessons!

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