Data Annotation Validation
Validate models with attributes.
Data Annotation Validation is a free C# Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C# Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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; }
}Validating Numbers With [Range]
[Range] restricts a numeric value to an inclusive minimum and maximum. It works with int, double, decimal and more.
Use it for ages, quantities, ratings and any bounded number.
public class ProductRequest
{
[Range(1, 1000, ErrorMessage = "Quantity must be between 1 and 1000.")]
public int Quantity { get; set; }
[Range(0.01, 9999.99)]
public decimal Price { get; set; }
}Validating Email With [EmailAddress]
[EmailAddress] checks that a string looks like a valid email address. Combine it with [Required] so the field is both present and well-formed.
public class ContactRequest
{
[Required]
[EmailAddress(ErrorMessage = "Please enter a valid email.")]
public string Email { get; set; }
}String Length Constraints
[StringLength] sets a maximum (and optional minimum) length for text. [MinLength] and [MaxLength] are simpler alternatives.
public class RegisterRequest
{
[Required]
[StringLength(20, MinimumLength = 3)]
public string Username { get; set; }
[MaxLength(500)]
public string Bio { get; set; }
}Pattern Matching With [RegularExpression]
[RegularExpression] validates a string against a regex pattern. It is ideal for formats like phone numbers, postal codes or slugs.
public class ProfileRequest
{
[RegularExpression(@"^[a-z0-9-]+$",
ErrorMessage = "Slug may only contain lowercase letters, digits and dashes.")]
public string Slug { get; set; }
}Comparing Two Fields With [Compare]
[Compare] ensures one property matches another. The classic case is confirming a password.
public class RegisterRequest
{
[Required]
public string Password { get; set; }
[Compare(nameof(Password), ErrorMessage = "Passwords do not match.")]
public string ConfirmPassword { get; set; }
}How ModelState Reports Errors
When validation fails, ASP.NET Core fills ModelState with the errors. In an API controller decorated with [ApiController], invalid requests automatically return a 400 response, so you rarely check it manually.
[ApiController]
[Route("api/[controller]")]
public class AccountController : ControllerBase
{
[HttpPost("register")]
public IActionResult Register(RegisterRequest request)
{
// [ApiController] already returned 400 if invalid
return Ok("Registered " + request.Username);
}
}Manual ModelState Checks
Without [ApiController] (for example in MVC controllers), you check ModelState.IsValid yourself and decide how to respond.
public IActionResult Register(RegisterRequest request)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
return Ok();
}Combining Multiple Annotations
Annotations stack. A single property can carry several attributes, and all of them must pass. Order does not matter for evaluation, but keep them readable.
public class SignupRequest
{
[Required]
[EmailAddress]
[StringLength(254)]
public string Email { get; set; }
[Required]
[Range(18, 120, ErrorMessage = "Must be 18 or older.")]
public int Age { get; set; }
}When Data Annotations Fall Short
Data Annotations are great for simple, declarative rules. But cross-property logic, database lookups, or conditional rules ("required only when X") quickly become awkward. That is where FluentValidation shines, which we cover next.
Quick Check
Test your understanding of data annotations.
Recap
You learned that Data Annotations declare validation rules as attributes: [Required] for presence, [Range] for numeric bounds, [EmailAddress] for email format, plus [StringLength], [RegularExpression] and [Compare]. With [ApiController], failures auto-return 400 via ModelState. For complex rules, reach for FluentValidation next.
Frequently asked questions
Is the “Data Annotation Validation” lesson free?
Yes — the full text of “Data Annotation Validation” is free to read here on the web, and the C# Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C# Academy course, upgrade to CoddyKit PRO.
What will I learn in “Data Annotation Validation”?
Validate models with attributes. You practise C# Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start C# Academy?
No prior experience is required. C# Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Data Annotation Validation” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this C# Academy lesson?
Yes. Every C# Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Data Annotation Validation
- FluentValidation Rules
- Custom and Conditional Rules
- Integrating Validation with APIs