ASP.NET  

How to Validate Models in ASP.NET Core Using Data Annotations?

Introduction

When building APIs using ASP.NET Core Web API, ensuring that incoming data is valid is extremely important. Invalid or incomplete data can cause bugs, security issues, and poor user experience.

This is where Model Validation in ASP.NET Core using Data Annotations becomes very useful.

Data Annotations allow you to define validation rules directly on your model classes. ASP.NET Core automatically checks these rules when a request is received and helps you return meaningful error messages.

What is Model Validation in ASP.NET Core?

Model validation is the process of checking whether the data sent by the client is correct and follows defined rules.

πŸ‘‰ Example:

  • Name should not be empty

  • Email should be valid

  • Age should be greater than 18

If the data does not meet these rules, the API returns validation errors.

What are Data Annotations?

Data Annotations in ASP.NET Core are attributes (decorators) that you apply to model properties to define validation rules.

These attributes come from the namespace:

using System.ComponentModel.DataAnnotations;

Why Use Data Annotations?

1. Simple and Easy to Use

You just add attributes to properties β€” no complex logic required.

2. Built-in Validation Support

ASP.NET Core automatically validates models using these attributes.

3. Clean and Maintainable Code

Validation rules stay close to the model, making code easier to read.

4. Automatic Error Responses

ASP.NET Core can automatically return 400 Bad Request when validation fails.

Common Data Annotation Attributes in ASP.NET Core

Let’s explore commonly used validation attributes.

1. [Required]

Ensures that a field is not null or empty.

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

πŸ‘‰ Use when a field is mandatory.

2. [StringLength]

Limits the length of a string.

[StringLength(50)]
public string Name { get; set; }

πŸ‘‰ You can also define minimum length.

3. [Range]

Validates numeric values within a range.

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

πŸ‘‰ Ensures value is between 18 and 60.

4. [EmailAddress]

Validates email format.

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

5. [Phone]

Validates phone numbers.

[Phone]
public string PhoneNumber { get; set; }

6. [RegularExpression]

Custom validation using regex.

[RegularExpression(@"^[a-zA-Z]+$")]
public string Name { get; set; }

πŸ‘‰ Allows only alphabets.

Step-by-Step Example: Model Validation

Let’s implement validation in a real example.

Step 1: Create Model

public class User
{
    [Required(ErrorMessage = "Name is required")]
    [StringLength(50, MinimumLength = 3)]
    public string Name { get; set; }

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

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

πŸ‘‰ Here we defined validation rules directly in the model.

Step 2: Use Model in Controller

[HttpPost]
public IActionResult CreateUser([FromBody] User user)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    return Ok("User created successfully");
}

Explanation

  • ModelState checks if validation passed

  • If invalid β†’ returns error details

Automatic Validation in ASP.NET Core

If you use [ApiController], validation is automatic.

[ApiController]
[Route("api/[controller]")]
public class UsersController : ControllerBase
{
}

πŸ‘‰ ASP.NET Core automatically returns 400 Bad Request if model is invalid.

No need to manually check ModelState.

Custom Error Messages

You can provide user-friendly messages.

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

πŸ‘‰ Improves user experience.

Handling Validation Errors Response

Default response:

{
  "errors": {
    "Name": ["The Name field is required."]
  }
}

πŸ‘‰ You can customize this response using middleware or filters.

Advanced Validation: Custom Validation Attribute

You can create your own validation logic.

public class MinimumAgeAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value is int age && age >= 18)
        {
            return ValidationResult.Success;
        }

        return new ValidationResult("Age must be at least 18");
    }
}

Use It

[MinimumAge]
public int Age { get; set; }

πŸ‘‰ Useful for business-specific validation rules.

Best Practices for Model Validation in ASP.NET Core

1. Use Data Annotations for Basic Validation

Keep simple validations inside models.

2. Use Custom Validators for Complex Logic

Do not overload models with complex rules.

3. Keep Models Clean and Focused

Avoid mixing business logic with validation.

4. Use DTOs for Validation

Separate API models from domain models.

5. Return Meaningful Error Messages

Helps frontend developers and users.

Common Mistakes to Avoid

  • ❌ Not validating input data

  • ❌ Ignoring ModelState

  • ❌ Writing validation logic in controllers

  • ❌ Not using DTOs

Real-World Use Case

In a real ASP.NET Core Web API application, model validation is used for:

  • User registration forms

  • Login APIs

  • Product creation

  • Order processing

πŸ‘‰ Validation ensures data consistency and prevents invalid data from entering the system.

Summary

Model validation in ASP.NET Core using Data Annotations is a simple and powerful way to ensure data correctness in your applications. By applying attributes like Required, Range, and EmailAddress, you can automatically validate incoming data with minimal code. Using best practices like DTOs, custom validation attributes, and meaningful error messages helps you build scalable, secure, and production-ready APIs.