Model Validation in ASP.NET Core MVC

Handling user input is a fundamental part of any web application. Whether it is a registration form, a login screen, or a product creation page, applications constantly receive data from users.

However, not all input is valid. Users may leave required fields empty, enter incorrect formats, or provide unexpected values. If such data is accepted without validation, it can lead to application errors, inconsistent data, and security issues.

This is where Model Validation becomes essential in ASP.NET Core MVC.

After Model Binding maps incoming request data to objects, Model Validation ensures that the data meets defined rules before it is processed.


What is Model Validation?

Model Validation is the process of verifying whether the data in a model satisfies predefined rules or constraints.

These rules are typically defined using attributes applied to model properties.

If the data does not meet these rules, the model is considered invalid and should not be processed further.


Why Model Validation is Important

Without validation, applications become vulnerable to incorrect and inconsistent data.

  • Users may submit incomplete forms
  • Invalid formats may break business logic
  • Incorrect data may be stored in the database
  • Security risks may increase

Validation ensures that only meaningful and expected data enters the system.


Using Data Annotations

To use validation attributes, include the following namespace:

using System.ComponentModel.DataAnnotations;

This namespace provides built-in attributes that define validation rules.


How Validation Works in MVC

Model Validation works together with Model Binding.

  1. User submits a form
  2. Model Binding maps data to the model
  3. Validation rules are applied
  4. If valid → controller proceeds
  5. If invalid → errors are returned to the view

The validation rules are defined using Data Annotations.


Model with Validation

using System.ComponentModel.DataAnnotations;

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

    [Required]
    [EmailAddress]
    public string Email { get; set; }

    [Required]
    [MinLength(6)]
    public string Password { get; set; }
}

These attributes define rules that are automatically checked when data is submitted.

What Happens Internally?

  • Model Binding creates the object
  • Validation checks each annotation
  • If any rule fails → ModelState becomes invalid
  • Error messages are generated

This process is automatic and requires minimal code.


Controller Validation Check

[HttpPost]
public IActionResult Register(User model)
{
    if (!ModelState.IsValid)
    {
        return View(model);
    }

    // Process valid data

    return RedirectToAction("Success");
}

The ModelState object stores validation results.


Displaying Validation Errors in Razor

<form method="post">

    <input name="Email" />

    <span>
        @Html.ValidationMessage("Email")
    </span>

    <button type="submit">
        Submit
    </button>

</form>

This displays validation messages near the input field.


Common Data Annotations

The following are commonly used Data Annotations along with their purpose and example usage:

Annotation Purpose Example Usage
[Required] Ensures the field is not empty [Required]
[StringLength] Controls min and max length [StringLength(50, MinimumLength = 5)]
[Range] Restricts value within range [Range(1, 100)]
[EmailAddress] Validates email format [EmailAddress]
[Compare] Compares two fields [Compare("Password")]
[RegularExpression] Custom pattern validation [RegularExpression(@"^[A-Za-z]+$")]
[DataType] Defines UI rendering type [DataType(DataType.Password)]
[Display] Sets display label [Display(Name="User Name")]

These annotations are applied directly on model properties and automatically used during validation.


Real-World Scenario

Consider a user registration form.

If the user submits the form without entering an email or enters an invalid format, the application should not accept the data.

Validation rules detect the issue and return appropriate error messages.

This ensures that only valid data is processed and stored.


Common Mistakes

  • Forgetting validation attributes
  • Not checking ModelState.IsValid
  • Mismatch between UI and model properties
  • Ignoring validation errors in UI

Summary

Model Validation is a critical feature in ASP.NET Core MVC that ensures the integrity and correctness of user input before it is processed by the application. It works closely with Model Binding, forming a seamless pipeline where incoming data is first mapped to a model and then validated against predefined rules.

By using Data Annotations, developers can define validation rules directly on model properties. These rules are automatically applied during the request lifecycle, reducing the need for manual validation logic and improving code readability.

In real-world applications, validation is essential for forms, user input processing, and maintaining consistency across the system.

Understanding Model Validation is crucial for building reliable and secure applications in ASP.NET Core MVC.