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

Explaining ASP.NET Core Server-Side Validation in Detail

ASP.NET Core is a powerful and flexible framework for building modern, cloud-based web applications. One critical aspect of any application, especially when it comes to web development, is ensuring data integrity and security. Data validation is an essential part of ensuring that user inputs conform to expected formats and values before they are processed by the application. In this guide, we will delve into server-side validation within ASP.NET Core. Server-side validation occurs on the server before data is processed, ensuring a robust security layer against malicious data.

Step 1: Setting Up Your ASP.NET Core Project

Before diving into validation, it’s important to ensure you have an ASP.NET Core application set up. Open Visual Studio and create a new project. Choose “ASP.NET Core Web App (Model-View-Controller)” if you want a traditional MVC structure.

Create ASP.NET Core MVC Project
Image 1: Creating a new ASP.NET Core MVC project in Visual Studio

Choose your project name, location, and solution name. Select .NET 6.0 (LTS) or another version you prefer.

Step 2: Creating the Model

The first step in validation is having a model that represents the data your user will input. In ASP.NET Core, you define these using C# classes. You can place these classes in a Models folder in your project.

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

    [Required(ErrorMessage = "Email is required.")]
    [EmailAddress(ErrorMessage = "Please enter a valid email address.")]
    public string Email { get; set; }

    [Required(ErrorMessage = "Password is required.")]
    [DataType(DataType.Password)]
    [StringLength(100, MinimumLength = 6, ErrorMessage = "Password must be at least 6 characters long.")]
    public string Password { get; set; }

    [Required(ErrorMessage = "Age is required.")]
    [Range(1, 120, ErrorMessage = "Age must be between 1 and 120.")]
    public int Age { get; set; }
}

In the above example, the User class is annotated with data annotations like Required, StringLength, EmailAddress, DataType, and Range to specify validation rules. These attributes are provided by the System.ComponentModel.DataAnnotations namespace, which you need to include.

Step 3: Creating the Controller

Next, create a controller to handle the user actions such as displaying forms and handling form submissions. Right-click on the Controllers folder in your project and add a new MVC Controller with actions, using the Entity Framework.

public class UserController : Controller
{
    [HttpGet]
    public IActionResult Register()
    {
        return View();
    }

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

        // If we got this far, something failed, redisplay form
        return View(user);
    }

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

Here, Register action method is overloaded. The [HttpGet] version renders a registration form, and the [HttpPost] version handles form submissions. Notice that the ModelState.IsValid property is used to check if the model passed validation. If it’s invalid, the controller returns the view, passing the user object to repopulate the form.

Step 4: Creating the View

You need a view for the registration form. Right-click inside the Register action and select “Add View” to create a new Razor view file. In this view, we’ll use HTML helpers to create the form and display validation messages.

@model User

<h2>Register</h2>
<form method="post" asp-action="Register">
    <div>
        <label asp-for="Name"></label>
        <input asp-for="Name" />
        <span asp-validation-for="Name"></span>
    </div>
    
    <div>
        <label asp-for="Email"></label>
        <input asp-for="Email" />
        <span asp-validation-for="Email"></span>
    </div>

    <div>
        <label asp-for="Password"></label>
        <input asp-for="Password" />
        <span asp-validation-for="Password"></span>
    </div>

    <div>
        <label asp-for="Age"></label>
        <input asp-for="Age" />
        <span asp-validation-for="Age"></span>
    </div>

    <button type="submit">Register</button>
</form>

In the form, asp-for tag helper is used to bind the form elements to the model properties. asp-validation-for tag helper displays the validation messages for the corresponding form elements. Note that we still need to include the necessary JavaScript files for client-side validation to work, but server-side validation is handled without JavaScript.

Step 5: Adding Validation Scripts

To enable client-side validation, you need to include jQuery and jQuery Validation scripts in your layout file. ASP.NET Core includes these scripts in the lib folder when you create a new project.

Open Views/Shared/_Layout.cshtml and add the following script bundles before the closing </body> tag:

@section Scripts {
    @{
        await Html.RenderPartialAsync("_ValidationScriptsPartial");
    }
}

In this example, _ValidationScriptsPartial is a partial view that contains script references for jQuery, jQuery Validation, and Unobtrusive AJAX.

Step 6: Testing Server-Side Validation

Now that everything is set up, you can run your application and test the server-side validation. Enter invalid data and submit the form. Notice that the form is validated on the server before processing the data. If the model is invalid, the form is redisplayed with error messages.

Validation Failure
Image 2: Validation failure showing error messages

Understanding Validation Attributes

Here’s a brief overview of the validation attributes mentioned in the model:

  • [Required]: Specifies that a field is required.
  • [StringLength]: Specifies the maximum number of characters allowed in a string.
  • [EmailAddress]: Ensures that the string follows the standard email format.
  • [DataType]: Specifies the type of data that the property represents.
  • [Range]: Constrains the value of a numeric property to be within a specified range.

ASP.NET Core provides many other validation attributes, such as:

  • [Compare]: Compares two properties to ensure they have the same value.
  • [RegularExpression]: Tests a field with a regular expression.
  • [Phone]: Ensures that a string is a phone number.
  • [Url]: Ensures that a string is a URL.
  • [MinLength], [MaxLength], [Min], [Max]: Provide minimum and maximum constraints for string, integer, and other data types.

Using Custom Validation Attributes

Sometimes, built-in validation attributes might not cover all your needs. In such cases, you can create custom validation attributes. Here’s how to create a custom validation attribute to ensure that the user’s name starts with a capital letter.

  1. Create a new class that inherits from ValidationAttribute.
public class CapitalizedAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var name = value as string;
        if (!string.IsNullOrEmpty(name) && char.IsUpper(name[0]))
        {
            return ValidationResult.Success;
        }

        return new ValidationResult(ErrorMessage);
    }
}
  1. Use the Capitalized attribute in the model.
public class User
{
    [Capitalized(ErrorMessage = "Name must start with a capital letter.")]
    [Required(ErrorMessage = "Name is required.")]
    [StringLength(50, MinimumLength = 2, ErrorMessage = "Name must be between 2 and 50 characters.")]
    public string Name { get; set; }
    //...
}

With custom validation attributes, you can create any rules you need to meet your application's specific validation requirements.

Server-Side Validation vs. Client-Side Validation

It's important to understand the differences between server-side and client-side validation:

  • Server-Side Validation: Happens on the server after the form is submitted. It ensures that the data is valid even if JavaScript is disabled or bypassed. This is the most reliable form of validation, as it doesn’t rely on the client.
  • Client-Side Validation: Happens in the user’s browser using JavaScript before the form is submitted. It provides immediate feedback to the user and improves the user experience. However, it can be bypassed and should not be relied upon for security.

Summary

In this guide, we’ve covered the following topics:

  1. Setting up an ASP.NET Core project.
  2. Creating a model with validation attributes.
  3. Creating a controller with action methods for rendering the form and handling submissions.
  4. Creating a view with HTML helpers for displaying the form and validation messages.
  5. Adding validation scripts for client-side validation.
  6. Understanding built-in and custom validation attributes.
  7. Comparing server-side and client-side validation.

By following these steps, you can implement robust server-side validation in your ASP.NET Core applications to ensure data integrity and security. Remember that server-side validation is essential for a secure application despite the use of client-side validation for better user experience. Happy coding!