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
MediumMove the title rules onto TaskInput, and add a new one: a title has at most 80 characters.
- You have a new file,
Validation.cs. ItsErrorsmethod turns the results into the dictionaryResults.ValidationProblemtakes. Where the comment says, callValidator.TryValidateObjectonmodelwith a newValidationContext(model),resultsandvalidateAllProperties: true. - At the top of
Program.cs, addusing System.ComponentModel.DataAnnotations;and giveTaskInput'sTitletwo attributes:[property: Required(ErrorMessage = "Title is required."), StringLength(80)]. - In POST and PUT, replace the
IsNullOrWhiteSpacecheck withvar errors = Validation.Errors(input);and answerResults.ValidationProblem(errors)when it is notnull.
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);