Course contentsShow
← C#
Lesson 1307 of 1,90812. Modern Frontend with Razor and BlazorFree lesson

Server-Side Validation Strategies

Implement data annotations to enforce server-side validation rules on form inputs.

In this lesson, you will learn how to use Data Annotations to enforce robust, server-side validation rules directly within your C# model classes.

The Importance of Server-Side Validation

While client-side validation provides immediate feedback, it is never a substitute for server-side security. Since a malicious user can easily bypass browser-based checks, you must re-verify that the incoming data adheres to your business requirements once it reaches your server.

In ASP.NET, we accomplish this by decorating our model properties with Data Annotations. These attributes act as a "contract" that the model binding system automatically enforces before your controller action code ever runs.

Implementing Data Annotations

To enforce rules, you apply attributes from the System.ComponentModel.DataAnnotations namespace to your model properties. If the incoming data violates these rules, the ModelState.IsValid property will automatically be set to false, allowing you to reject the request immediately.

Consider a registration model:

public class UserRegistration
{
    [Required(ErrorMessage = "Username is mandatory.")]
    [StringLength(20, MinimumLength = 3)]
    public string Username { get; set; }

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

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

Enforcing the Rules in the Controller

When a user submits a form, you check the model's integrity in your controller action:

[HttpPost]
public IActionResult Register(UserRegistration model)
{
    if (!ModelState.IsValid)
    {
        // Return the user to the form to display validation errors
        return View(model);
    }

    // Proceed with secure processing
    return RedirectToAction("Success");
}

By defining these rules at the model level, you create a centralized "source of truth." This keeps your controller logic clean while ensuring that regardless of where the data originates, it must satisfy your specified constraints before the application proceeds. This approach is fundamental to maintaining data integrity and protecting your server from malformed or malicious input.

Key Takeaway: Always treat client-side validation as a user-experience enhancement, while relying on server-side Data Annotations as your non-negotiable security enforcement layer.