Menu
CoddyTech

Validation Attributes

Part of the REST APIs section of Coddy's ASP.NET Core journey. Lesson 7 of 20.

Writing every rule as an if grows long. Data annotations put the rules on the type as attributes, from System.ComponentModel.DataAnnotations, and Validator checks an object against them.

record SignupInput(
    [property: Required, EmailAddress] string Email,
    [property: Range(13, 120)] int Age);

var results = new List<ValidationResult>();
Validator.TryValidateObject(input, new ValidationContext(input), results,
    validateAllProperties: true);

In a positional record, property: puts the attribute on the property, which is where Validator looks. Without validateAllProperties: true it checks [Required] only. Each broken rule adds a ValidationResult with the property's name and a message. .NET 10 also has builder.Services.AddValidation(), which checks endpoint parameters for you, but for your own types it needs a source generator. The runner here does not run source generators, so you call Validator yourself.

challenge icon

Challenge

Medium

Move the title rules onto TaskInput, and add a new one: a title has at most 80 characters.

  1. You have a new file, Validation.cs. Its Errors method turns the results into the dictionary Results.ValidationProblem takes. Where the comment says, call Validator.TryValidateObject on model with a new ValidationContext(model), results and validateAllProperties: true.
  2. At the top of Program.cs, add using System.ComponentModel.DataAnnotations; and give TaskInput's Title two attributes: [property: Required(ErrorMessage = "Title is required."), StringLength(80)].
  3. In POST and PUT, replace the IsNullOrWhiteSpace check with var errors = Validation.Errors(input); and answer Results.ValidationProblem(errors) when it is not null.

A title of 81 characters now answers 400 with:

"errors": { "title": ["The field Title must be a string with a maximum length of 80."] }

Try it: press Run and POST a body whose title is 81 letters to /api/tasks: 400 and the error above. POST { "title": "" }: 400 with Title is required., as before. POST { "title": "Order new chairs" }: 201.

Try it yourself

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

var tasks = new List<TaskItem>
{
    new(1, "Write the project brief", false),
    new(2, "Book the meeting room", true),
    new(3, "Send the invoice", false),
};
var nextId = 4;

app.MapGet("/api/tasks", () => tasks);

app.MapGet("/api/tasks/{id:int}", (int id) =>
{
    var task = tasks.Find(t => t.Id == id);
    return task is null ? Results.NotFound() : Results.Ok(task);
});

app.MapPost("/api/tasks", (TaskInput input) =>
{
    if (string.IsNullOrWhiteSpace(input.Title))
    {
        return Results.ValidationProblem(new Dictionary<string, string[]>
        {
            ["title"] = ["Title is required."],
        });
    }
    var task = new TaskItem(nextId++, input.Title, input.Done);
    tasks.Add(task);
    return Results.Created($"/api/tasks/{task.Id}", task);
});

app.MapPut("/api/tasks/{id:int}", (int id, TaskInput input) =>
{
    if (string.IsNullOrWhiteSpace(input.Title))
    {
        return Results.ValidationProblem(new Dictionary<string, string[]>
        {
            ["title"] = ["Title is required."],
        });
    }
    var index = tasks.FindIndex(t => t.Id == id);
    if (index == -1) return Results.NotFound();
    tasks[index] = new TaskItem(id, input.Title, input.Done);
    return Results.Ok(tasks[index]);
});

app.MapPatch("/api/tasks/{id:int}", (int id, TaskPatch patch) =>
{
    var index = tasks.FindIndex(t => t.Id == id);
    if (index == -1) return Results.NotFound();
    var task = tasks[index];
    tasks[index] = task with
    {
        Title = patch.Title ?? task.Title,
        Done = patch.Done ?? task.Done,
    };
    return Results.Ok(tasks[index]);
});

app.MapDelete("/api/tasks/{id:int}", (int id) =>
{
    var removed = tasks.RemoveAll(t => t.Id == id);
    return removed == 0 ? Results.NotFound() : Results.NoContent();
});

app.Run();

record TaskItem(int Id, string Title, bool Done);
record TaskInput(string Title, bool Done);
record TaskPatch(string? Title, bool? Done);

All lessons in REST APIs