ASP.NET Core Client side Validation Step by step Implementation and Top 10 Questions and Answers
 Last Update: April 01, 2025      12 mins read      Difficulty-Level: beginner

ASP.NET Core Client-Side Validation: A Detailed Step-by-Step Guide for Beginners

Client-side validation plays an extremely important role in web applications by providing immediate feedback to users, reducing server load, and enhancing user experience. In ASP.NET Core, client-side validation is seamlessly integrated with model validation and can be enabled easily with minimal configuration. This guide will walk you through the process of setting up and using client-side validation in ASP.NET Core applications.

Understanding Model Validation

Before diving into client-side validation, it's essential to understand model validation in ASP.NET Core. Server-side validation is crucial because it ensures data integrity and security, preventing malicious or incorrect data from being processed. Client-side validation, on the other hand, enhances user experience by providing immediate feedback.

ASP.NET Core uses DataAnnotation attributes to define validation rules for model properties. These attributes are a part of the System.ComponentModel.DataAnnotations namespace and can be applied directly to your model properties. Here's a simple example:

public class Person
{
    [Required]
    public string Name { get; set; }

    [Range(18, 100)]
    public int Age { get; set; }

    [RegularExpression(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$", ErrorMessage = "Invalid email address.")]
    public string Email { get; set; }
}

In this example, the Person model has three properties: Name, Age, and Email. The Name property is required, Age must be a number between 18 and 100, and Email must match a specified regular expression pattern.

Setting Up ASP.NET Core MVC Project

To begin, create a new ASP.NET Core MVC project using Visual Studio or the .NET Core CLI:

  • Visual Studio: Create a new project by selecting "ASP.NET Core Web App (Model-View-Controller)" under C# > Web.
  • .NET Core CLI: Use the command dotnet new mvc -n MyValidationApp.

Once the project is created, add a new model class (for example, Person) and apply validation attributes as shown earlier.

Adding Client-Side Validation Libraries

ASP.NET Core automatically references the necessary JavaScript libraries for client-side validation through the asp-validation-summary and asp-validation-for HTML helpers. By default, these helpers use the jQuery Validation library along with the jQuery Unobtrusive Validation adapter. These libraries are included via the Microsoft.AspNetCore.Mvc.NewtonsoftJson package, which is part of the default project template.

Ensure that your _Layout.cshtml file includes references to these libraries:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewData["Title"] - MyValidationApp</title>
    <link href="~/lib/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" />
    <script src="~/lib/jquery/dist/jquery.min.js"></script>
    <script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
    <script src="~/lib/jquery-validation-unobtrusive/dist/jquery.validate.unobtrusive.min.js"></script>
</head>
<body>
    <div>
        @RenderBody()
    </div>
</body>
</html>

Creating a Controller and Views

Add a new controller (PersonController) with actions to handle displaying and processing the form:

using Microsoft.AspNetCore.Mvc;

namespace MyValidationApp.Controllers
{
    public class PersonController : Controller
    {
        [HttpGet]
        public IActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public IActionResult Create(Person person)
        {
            if (ModelState.IsValid)
            {
                // Process the valid data
                return RedirectToAction(nameof(Create)); // Redirect to the same form to clear inputs
            }

            // If the model state is invalid, return the view with the validation errors
            return View(person);
        }
    }
}

Create a corresponding view (Create.cshtml) that uses the asp-for tag helpers for model binding and the asp-validation-for tag helpers for validation messages:

@model MyValidationApp.Models.Person

<form action="/Person/Create" method="post">
    <div class="form-group">
        <label asp-for="Name"></label>
        <input asp-for="Name" class="form-control" />
        <span asp-validation-for="Name" class="text-danger"></span>
    </div>
    <div class="form-group">
        <label asp-for="Age"></label>
        <input asp-for="Age" class="form-control" />
        <span asp-validation-for="Age" class="text-danger"></span>
    </div>
    <div class="form-group">
        <label asp-for="Email"></label>
        <input asp-for="Email" class="form-control" />
        <span asp-validation-for="Email" class="text-danger"></span>
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
</form>
<partial name="_ValidationScriptsPartial" />

The asp-for tag helper binds the input element to the specified model property, while the asp-validation-for tag helper displays validation messages next to each input field if the validation fails.

The _ValidationScriptsPartial partial view (which is included in the _Layout.cshtml file) ensures that the validation scripts are loaded only in pages that require them:

environment names="Development">
    <script src="~/lib/jquery-validation/dist/jquery.validate.js"></script>
    <script src="~/lib/jquery-validation-unobtrusive/dist/jquery.validate.unobtrusive.js"></script>
</environment>
<environment names="Staging,Production">
    <script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.17.0/jquery.validate.min.js"
            asp-fallback-src="~/lib/jquery-validation/dist/jquery.validate.min.js"
            asp-fallback-test="window.jQuery && window.jQuery.validator"
            crossorigin="anonymous"
            integrity="sha384-rZfj/ogBloos6w9SmQ4lEI8w9trhr6SEbVQO+dyJH7WGXH/i5yZ3mB1Bj5GZvJq0Uw">
    </script>
    <script src="https://ajax.aspnetcdn.com/ajax/jquery.validation.unobtrusive/3.2.10/jquery.validate.unobtrusive.min.js"
            asp-fallback-src="~/lib/jquery-validation-unobtrusive/dist/jquery.validate.unobtrusive.min.js"
            asp-fallback-test="window.jQuery && window.jQuery.validator && window.jQuery.validator.unobtrusive"
            crossorigin="anonymous"
            integrity="sha384-3pJ10xWbLXZ5r7JQp16v6J7K4R6B0Z5v10eW90+1PZ3B0G5Z6J7K4R6B0Z5v10eW90+1PZ3B0G5Z6N7R7">
    </script>
</environment>

This partial view uses the environment tag helper to include the validation scripts in different environments (development, staging, and production). In development, local copies of the scripts are used, while in production, scripts are served from a CDN for better performance and availability.

Testing Client-Side Validation

Run the application and navigate to the form page (Person/Create). Try submitting the form with invalid data (e.g., an empty name field, an age outside the specified range, or an invalid email address). The form should validate the input fields as you type and display validation messages next to the respective input fields.

Validation in Action

Here's a breakdown of the client-side validation process:

  1. Form Submission: When the form is submitted, the data is sent to the server for processing.
  2. Model Binding: ASP.NET Core binds the form data to the Person model.
  3. Validation: The validation attributes defined on the Person model properties are checked.
  4. JavaScript Validation: If the ModelState.IsValid property is false, the form submission is halted, and the client-side validation libraries display error messages.
  5. Feedback to User: Users are notified of the validation errors, and they can correct the issues and resubmit the form if needed.

Customizing Client-Side Validation Messages

You can customize client-side validation messages by providing the ErrorMessage property to the validation attributes:

public class Person
{
    [Required(ErrorMessage = "Please enter your name.")]
    public string Name { get; set; }

    [Range(18, 100, ErrorMessage = "Your age must be between 18 and 100.")]
    public int Age { get; set; }

    [RegularExpression(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$", ErrorMessage = "The email address is invalid.")]
    public string Email { get; set; }
}

These custom messages will be displayed instead of the default validation messages when the form is submitted with invalid data.

Handling Complex Validation Scenarios

For more complex validation scenarios, you can create custom validation attributes by inheriting from the ValidationAttribute class. Here's an example of a custom validation attribute that ensures the Name property does not contain any numeric characters:

using System.ComponentModel.DataAnnotations;

public class NoNumbersAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value is string name && name.Any(char.IsDigit))
        {
            return new ValidationResult(ErrorMessage);
        }

        return ValidationResult.Success;
    }
}

You can then apply this custom validation attribute to the Name property:

public class Person
{
    [Required(ErrorMessage = "Please enter your name.")]
    [NoNumbers(ErrorMessage = "Name must not contain any numbers.")]
    public string Name { get; set; }

    [Range(18, 100, ErrorMessage = "Your age must be between 18 and 100.")]
    public int Age { get; set; }

    [RegularExpression(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$", ErrorMessage = "The email address is invalid.")]
    public string Email { get; set; }
}

For client-side validation of custom attributes, you need to write additional JavaScript code to handle the custom validation rules. Here's an example of how you can add client-side validation for the NoNumbersAttribute:

  1. Create a Custom Validation Adapter: Create a new JavaScript file (e.g., custom-validations.js) and define a validation adapter for the custom attribute:
$.validator.unobtrusive.adapters.add('noNumbers', ['errormessage'], function (options) {
    options.rules['noNumbers'] = true;
    options.messages['noNumbers'] = options.params.errormessage;
});

$.validator.addMethod('noNumbers', function (value, element, params) {
    return !/\d/.test(value);
});
  1. Include the Custom Validation Script: Ensure that the custom validation script is included in the _ValidationScriptsPartial file:
<script src="~/js/custom-validations.js"></script>

With these changes, the client-side validation will now handle the NoNumbers attribute, providing immediate feedback to users when the Name field contains numeric characters.

Disabling Client-Side Validation

In some cases, you may want to disable client-side validation for specific fields or the entire form. You can achieve this by adding the novalidate attribute to the form or individual input elements.

Disabling Client-Side Validation for the Entire Form:

<form action="/Person/Create" method="post" novalidate>
    <!-- Form elements -->
</form>

Disabling Client-Side Validation for Specific Fields:

<input asp-for="Name" class="form-control" novalidate />

By adding the novalidate attribute, client-side validation will be disabled, and the form will only be validated on the server side. However, it's generally recommended to keep client-side validation enabled to provide a better user experience.

Summary

Client-side validation is a powerful feature in ASP.NET Core that enhances the user experience by providing immediate feedback and reducing server load. In this guide, you learned how to set up and use client-side validation in ASP.NET Core MVC applications by leveraging DataAnnotation attributes, jQuery Validation, and jQuery Unobtrusive Validation libraries.

Key points covered in this guide:

  • Understanding model validation and the role of DataAnnotation attributes in defining validation rules.
  • Creating a new ASP.NET Core MVC project and setting up the necessary libraries for client-side validation.
  • Designing a controller and views to handle form submissions and display validation messages.
  • Customizing client-side validation messages and handling complex validation scenarios.
  • Disabling client-side validation for specific fields or the entire form.

By following these steps, you can effectively implement client-side validation in your ASP.NET Core applications, providing a better user experience and ensuring data integrity.