Search⌘ K
AI Features

Adding Validation to Updating a Question

Explore how to implement model validation in ASP.NET Core API requests to ensure that updates to questions and answers meet defined data requirements. Learn to use validation attributes like Required and StringLength, understand nullable property handling, and test your API endpoints effectively.

Steps to add validation to update a question

Let’s add validation to the request for updating a question:

  1. Open QuestionPutRequest.cs and add the following using statement:

C#
using System.ComponentModel.DataAnnotations;
  1. Add the following validation attribute to the Title property:

C#
public class QuestionPutRequest
{
[StringLength(100)]
public string Title { get; set; }
public string Content { get; set; }
}

We are making sure that a new title doesn’t exceed 100 characters.

  1. Let’s run the app and give this a try by updating a question to have a very long title:

Validation error when updating a question with a long title
Validation error when updating a question with a long title

A validation error is returned as expected.

  1. Stop the app running so that we’re ready to add the ...