Validation and Data Annotations

Intermediate 20 min read Lesson 5 of 8

What are Data Annotations?

Data Annotations are attributes used to enforce validation rules on model properties.

Common Validation Attributes

Required

public class Product
{
    [Required(ErrorMessage = "Name is required")]
    public string Name { get; set; }
}

String Length

[StringLength(100, MinimumLength = 2, ErrorMessage = "Name must be between 2 and 100 characters")]
public string Name { get; set; }

Range

[Range(0, 1000, ErrorMessage = "Price must be between 0 and 1000")]
public decimal Price { get; set; }

Email

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

Regular Expression

[RegularExpression("^[A-Z]+[a-zA-Z]*$", ErrorMessage = "Name must start with a capital letter")]
public string Name { get; set; }

Compare

public string Password { get; set; }

[Compare("Password", ErrorMessage = "Passwords do not match")]
public string ConfirmPassword { get; set; }

Validation in Razor Pages

Model with Validation

public class Product
{
    [Required]
    [StringLength(100)]
    public string Name { get; set; }
    
    [Required]
    [Range(0.01, 9999.99)]
    public decimal Price { get; set; }
    
    [Required]
    public int CategoryId { get; set; }
}

Page Handler

public class CreateModel : PageModel
{
    [BindProperty]
    public Product Product { get; set; }
    
    public IActionResult OnPost()
    {
        if (!ModelState.IsValid)
            return Page();
        
        // Save product
        return RedirectToPage("Index");
    }
}

View with Validation

<div asp-validation-summary="ModelOnly" class="text-danger"></div>

<div class="form-group">
    <label asp-for="Product.Name"></label>
    <input asp-for="Product.Name" class="form-control" />
    <span asp-validation-for="Product.Name" class="text-danger"></span>
</div>

<div class="form-group">
    <label asp-for="Product.Price"></label>
    <input asp-for="Product.Price" class="form-control" />
    <span asp-validation-for="Product.Price" class="text-danger"></span>
</div>

Custom Validation

// Custom Validation Attribute
public class AgeRangeAttribute : ValidationAttribute
{
    private readonly int _minAge;
    private readonly int _maxAge;
    
    public AgeRangeAttribute(int minAge, int maxAge)
    {
        _minAge = minAge;
        _maxAge = maxAge;
    }
    
    protected override ValidationResult IsValid(object value, ValidationContext context)
    {
        var age = (int)value;
        if (age < _minAge || age > _maxAge)
            return new ValidationResult($"Age must be between {_minAge} and {_maxAge}");
        return ValidationResult.Success;
    }
}

// Usage
[AgeRange(18, 65, ErrorMessage = "Age must be between 18 and 65")]
public int Age { get; set; }
Key Takeaway

Data Annotations provide a clean, declarative way to implement validation in your application.

Test Your Knowledge - Take Quiz