29 Using model validation

This chapter covers

  • Understanding the ASP.NET Core data validation features
  • Applying validation to form data
  • Displaying validation errors to the user
  • Explicitly validating data in a controller or Razor Page
  • Specifying validation rules using attributes
  • Using JavaScript to perform client-side validation

In the previous chapter, I showed you how the model binding process creates objects from HTTP requests. Throughout that chapter, I simply displayed the data that the application received. That’s because the data that users provide should not be used until it has been inspected to ensure that the application is able to use it. The reality is that users will often enter data that isn’t valid and cannot be used, which leads me to the topic of this chapter: model validation.

Model validation is the process of ensuring the data received by the application is suitable for binding to the model and, when this is not the case, providing useful information to the user that will help explain the problem.

29.1 Preparing for this chapter

29.1.1 Dropping the database

29.1.2 Running the example application

29.2 Understanding the need for model validation

29.3 Validating data

29.3.1 Displaying validation messages

29.3.2 Understanding the implicit validation checks

29.3.3 Performing explicit validation

29.3.4 Configuring the default validation error messages

29.3.4 Displaying property-level validation messages

29.3.5 Displaying model-level messages

29.4 Explicitly validating data in a Razor Page

29.5 Specifying validation rules using metadata

29.5.1 Creating a custom property validation attribute

29.5.2 Creating a custom model validation attribute

29.6 Performing client-side validation

29.7 Performing remote validation

29.7.1 Performing remote validation in Razor Pages

Summary