Asp.Net Core Server Side Validation Complete Guide

 Last Update:2025-06-23T00:00:00     .NET School AI Teacher - SELECT ANY TEXT TO EXPLANATION.    7 mins read      Difficulty-Level: beginner

Understanding the Core Concepts of ASP.NET Core Server side Validation

ASP.NET Core Server-Side Validation: Detailed Explanation and Important Information

1. Why Use Server-Side Validation?

Even though client-side validation (such as JavaScript) can improve the user experience by providing immediate feedback, it is inherently insecure because users can manipulate the client code. Server-side validation, therefore, is essential for validating data before interacting with the server or database. This method helps prevent SQL injection, cross-site scripting (XSS), and other malicious attacks.

2. Built-in Validation Attributes in ASP.NET Core

ASP.NET Core provides numerous built-in validation attributes that simplify the process of implementing server-side validation. Here are some important ones:

  • [Required]: Ensures that the property is not null, empty, or whitespace.
  • [StringLength]: Specifies the maximum and minimum length of string properties.
  • [Range]: Restricts the value of a numeric property to a specific range.
  • [Compare]: Used to compare the value of two properties (commonly used for password confirmation).
  • [EmailAddress]: Validates that the property value is a valid email address.
  • [Phone]: Ensures that the property value is a valid phone number.
  • [Url]: Validates that the property value is a valid URL.
  • [RegularExpression]: Uses a regular expression to validate the property value.
  • [Remote]: Calls a server-side method to validate the property value on the client-side. This can be useful if the validation involves complex logic.

3. Custom Validation Attributes

When built-in validation attributes are not sufficient, you can create custom attributes to implement more specific rules. To create a custom validation attribute, you need to derive from the ValidationAttribute class and override the IsValid method.

Example of a custom validation attribute:

using System.ComponentModel.DataAnnotations;

public class DateInFutureAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        DateTime date = Convert.ToDateTime(value);
        if (date <= DateTime.Now)
        {
            return new ValidationResult("Date must be in the future.");
        }

        return ValidationResult.Success;
    }
}

Usage:

public class Event
{
    [DateInFuture(ErrorMessage = "The event date must be in the future.")]
    public DateTime EventDate { get; set; }
}

4. Validating Models in ASP.NET Core

In ASP.NET Core MVC, validation is typically performed on models that represent the data. You can use the ModelState.IsValid property to determine if the model has passed validation in the controller action. Here’s an example:

public class Product
{
    [Required(ErrorMessage = "Product name is required.")]
    public string Name { get; set; }

    [Range(1, int.MaxValue, ErrorMessage = "Price must be greater than zero.")]
    public decimal Price { get; set; }
}

Controller action:

[HttpPost]
public IActionResult Create(Product product)
{
    if (ModelState.IsValid)
    {
        // Save product to database
        return RedirectToAction("Index");
    }

    return View(product);
}

5. Display Validation Errors

Once validation fails, it's important to display the validation errors to the user. In Razor Views, you can use the Html.ValidationSummary() method to display all validation messages, or Html.ValidationMessageFor() to display the message for a specific property.

Example:

<!DOCTYPE html>
<html>
<head>
    <title>Create Product</title>
</head>
<body>
    <form method="post" asp-action="Create">
        <div>
            <label asp-for="Name">Product Name</label>
            <input type="text" asp-for="Name" />
            <span asp-validation-for="Name" class="text-danger"></span>
        </div>
        <div>
            <label asp-for="Price">Price</label>
            <input type="number" asp-for="Price" />
            <span asp-validation-for="Price" class="text-danger"></span>
        </div>
        <button type="submit">Create</button>
    </form>
    <div asp-validation-summary="ModelOnly" class="text-danger"></div>
</body>
</html>

6. Data Annotations vs. Fluent API Validation

While data annotations provide a quick and easy way to define validation rules, the Fluent API offers more flexibility and power. The Fluent API is typically used within Entity Framework Core configurations, where you can define validation rules directly in your DbContext classes.

Example using Fluent API:

public class ProductConfiguration : IEntityTypeConfiguration<Product>
{
    public void Configure(EntityTypeBuilder<Product> builder)
    {
        builder.Property(p => p.Name)
               .IsRequired()
               .HasMaxLength(255);

        builder.Property(p => p.Price)
               .IsRequired()
               .HasRange(1, int.MaxValue);
    }
}

7. Combining Client-Side and Server-Side Validation

For the best user experience, it's recommended to use both client-side and server-side validation. Client-side validation provides immediate feedback, improving UX, while server-side validation ensures security and data integrity.

Here’s a simple example of how to enable client-side validation in ASP.NET Core MVC:

Online Code run

🔔 Note: Select your programming language to check or run code at

💻 Run Code Compiler

Step-by-Step Guide: How to Implement ASP.NET Core Server side Validation

Step 1: Create a New ASP.NET Core MVC Project

  1. Open Visual Studio and create a new project.
  2. Choose ASP.NET Core Web App (Model-View-Controller) and click Next.
  3. Name your project (e.g., ServerSideValidationExample) and click Create.
  4. Select the target framework (e.g., .NET 6.0 or later) and click Create.

Step 2: Define a Model

Create a model that will represent the data you want to validate.

  1. In the ServerSideValidationExample project, create a new folder called Models.
  2. Add a new class to the Models folder named Product.cs:
using System.ComponentModel.DataAnnotations;

namespace ServerSideValidationExample.Models
{
    public class Product
    {
        [Required(ErrorMessage = "Product name is required.")]
        [StringLength(50, MinimumLength = 2, ErrorMessage = "Product name must be between 2 and 50 characters.")]
        public string Name { get; set; }

        [Range(1, 100000, ErrorMessage = "Price must be between 1 and 100,000.")]
        public decimal Price { get; set; }

        [Required(ErrorMessage = "Category is required.")]
        public string Category { get; set; }
    }
}

Step 3: Create a Controller

Create a controller to handle requests related to Product.

  1. In the ServerSideValidationExample project, create a new folder called Controllers.
  2. Add a new controller class to the Controllers folder named ProductsController.cs:
using Microsoft.AspNetCore.Mvc;
using ServerSideValidationExample.Models;

namespace ServerSideValidationExample.Controllers
{
    public class ProductsController : Controller
    {
        public IActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public IActionResult Create(Product product)
        {
            if (ModelState.IsValid)
            {
                // If the model is valid, process the data (e.g., save to database)
                // For this example, we will just redirect to a success page.
                return RedirectToAction("Success");
            }

            // If the model is not valid, return to the Create view with validation errors
            return View(product);
        }

        public IActionResult Success()
        {
            return View();
        }
    }
}

Step 4: Create Views

Create views for the ProductsController.

  1. In the ServerSideValidationExample project, create a new folder called Views if it doesn't already exist.
  2. Inside the Views folder, create another folder named Products.
  3. Add a new Razor View named Create.cshtml to the Products folder:
@model ServerSideValidationExample.Models.Product

@{
    ViewData["Title"] = "Create Product";
}

<h2>Create Product</h2>

<form asp-action="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="Price"></label>
        <input asp-for="Price" class="form-control" />
        <span asp-validation-for="Price" class="text-danger"></span>
    </div>
    <div class="form-group">
        <label asp-for="Category"></label>
        <input asp-for="Category" class="form-control" />
        <span asp-validation-for="Category" class="text-danger"></span>
    </div>
    <button type="submit" class="btn btn-primary">Create</button>
</form>

@section Scripts {
    <partial name="_ValidationScriptsPartial" />
}
  1. Add another Razor View named Success.cshtml to the Products folder:
@{
    ViewData["Title"] = "Success";
}

<h2>Product Created Successfully!</h2>
<p>The product has been successfully created.</p>

Step 5: Configure Validation Scripts

Ensure that the validation scripts are included in your project.

  1. Open the _Layout.cshtml file located in the Views/Shared folder.
  2. Add the following line to include jQuery and jQuery Validation scripts:

Top 10 Interview Questions & Answers on ASP.NET Core Server side Validation

Top 10 Questions and Answers on ASP.NET Core Server-Side Validation

1. What is Server-Side Validation in ASP.NET Core?

2. How Does ASP.NET Core Perform Server-Side Validation?

Answer: ASP.NET Core uses the Data Annotations API to perform server-side validation. This involves adding validation attributes to model properties. When the server receives a POST request, it automatically validates the model against these attributes, and if validation fails, the controller action returns the form with validation error messages.

3. What Are the Common Data Annotations Used in ASP.NET Core?

Answer: Some common data annotations include:

  • [Required]: Ensures that the field is not empty.
  • [StringLength(maximumLength)]: Limits the length of a string.
  • [Range(min, max)]: Specifies a numeric range.
  • [EmailAddress]: Validates that the field is an email address.
  • [RegularExpression]: Uses a custom regular expression pattern.
  • [Compare]: Ensures that the value of one property matches the value of another property.

4. How Can You Validate a Model Using Data Annotations in ASP.NET Core?

Answer: To validate a model using data annotations, you simply decorate the model properties with the appropriate attributes. Here’s a basic example:

public class User
{
    [Required(ErrorMessage = "Name is required.")]
    public string Name { get; set; }

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

    [EmailAddress(ErrorMessage = "Invalid Email Address.")]
    public string Email { get; set; }
}

When the User model is passed to a controller action, ASP.NET Core automatically checks the data annotations and runs the validations.

5. How Can You Handle Validation in the Controller?

Answer: In the controller action, you can check ModelState.IsValid to see if the model passed validation. Here’s an example:

[HttpPost]
public IActionResult Register(User user)
{
    if (ModelState.IsValid)
    {
        _repository.AddUser(user);
        return RedirectToAction("Success");
    }

    // If validation fails, return the view with the model and validation errors
    return View(user);
}

If validation fails, the user is returned to the form with the original input and error messages.

6. Can You Custom Validate a Property in ASP.NET Core?

Answer: Yes, you can create custom validation attributes by inheriting from ValidationAttribute. Here’s an example of a custom attribute to validate a username:

public class UsernameAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        string username = value as string;
        if (username == null || !username.StartsWith("@"))
        {
            return new ValidationResult("Username must start with '@'.");
        }

        return ValidationResult.Success;
    }
}

Use it like any other data annotation:

[Username]
public string Username { get; set; }

7. What Is the Role of ValidationResult in ASP.NET Core Validation?

Answer: ValidationResult is a class used in server-side validation to indicate the result of a validation check. It can either be ValidationResult.Success if validation passed, or an instance of ValidationResult with an error message if validation failed.

8. How Can You Validate Complex Types or Nested Objects in ASP.NET Core?

Answer: ASP.NET Core automatically validates complex types and nested objects. When you add validation attributes to properties within nested objects, the framework performs the necessary validation recursively.

Example:

public class User
{
    [Required]
    public PersonalInfo Info { get; set; }
}

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

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

If Info is null or Info.Age is outside the specified range, validation will fail.

9. Can ASP.NET Core Validate Collections?

Answer: Yes, ASP.NET Core can validate collections. You can use the ValidatableObject<T> base class within your collection items. Alternatively, you can manually invoke validation on each item in the collection.

Example with ValidatableObject<T>:

public class User
{
    [Required]
    public List<Contact> Contacts { get; set; }
}

public class Contact : IValidatableObject
{
    public string Name { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (string.IsNullOrEmpty(Name))
        {
            yield return new ValidationResult("Name is required.");
        }
    }
}

10. What Happens If Validation Fails in ASP.NET Core?

Answer: If validation fails, ModelState.IsValid is false, and the controller can take actions such as re-rendering the view with the original input and validation error messages. Additionally, the ModelState dictionary will contain the validation errors, which can be displayed to the user.

You May Like This Related .NET Topic

Login to post a comment.