0Pricing
C# Academy · Lesson

Data Annotation Validation

Validate models with attributes.

What Is Data Annotation Validation?

Data Annotations are attributes you place on model properties to declare validation rules directly in your C# classes. ASP.NET Core reads these attributes during model binding and validates incoming requests automatically.

They live in the System.ComponentModel.DataAnnotations namespace.

using System.ComponentModel.DataAnnotations;

public class RegisterRequest
{
    [Required]
    public string Username { get; set; }
}

The [Required] Attribute

[Required] ensures a property is not null (and not an empty string by default). If the client omits the field, model validation fails before your action runs.

You can customize the message with ErrorMessage.

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

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

All lessons in this course

  1. Data Annotation Validation
  2. FluentValidation Rules
  3. Custom and Conditional Rules
  4. Integrating Validation with APIs
← Back to C# Academy