Adding validation to posting a question

We can add validation to a model by adding validation attributes to properties in the model that specify rules that should be adhered to. Let's add validation to the request for posting a question:

  1. Open QuestionPostRequest.cs and add the following using statement:
using System.ComponentModel.DataAnnotations;

This namespace gives us access to the validation attributes.

  1. Add a Required attribute just above the Title property:
[Required]
public string Title { get; set; }

The Required attribute will check that the Title property is not an empty string or null.

  1. Before we try this out, put a breakpoint on the first statement within the PostQuestion action method in QuestionsController.cs.
  2. Let's run the app and try to post a question without a title in Postman:

We get a response with HTTP status code 400 as expected with great information about the problem in the response.

Notice also that the breakpoint wasn't reached. This is because ASP.NET Core checked the model, determined that it was invalid, and returned a bad request response before the action method was invoked.

  1. Let's stop the app from running and implement another validation check on the title:
[Required]
[StringLength(100)]
public string Title { get; set; }

This check will ensure the title doesn't have more than 100 characters. A title containing more than 100 characters would cause a database error, so this is a valuable check.

  1. A question must also have some content, so let's add a Required attribute to this:
[Required]
public string Content { get; set; }
  1. We can add a custom message to a validation attribute. Let's add a custom message to the validation on the Content property:
[Required(ErrorMessage = 
"Please include some content for the question")
]
public string Content { get; set; }
  1. Let's run the app and try posting a new question without any content:

We get our custom message in the response as expected.

  1. Let's stop the running app.

The UserId, UserName, and Created properties should really be required properties as well. However, we aren't going to add validation attributes on them because we are going to work on them later in this chapter.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.92.57