left-icon

ASP.NET Web API Succinctly®
by Emanuele DelBono

Previous
Chapter

of
A
A
A

CHAPTER 6

Model Validation

Model Validation


The attributes

As in ASP.NET, MVC models can be validated when they enter the Web API pipeline. To define the validation, our model must be decorated with attributes from the namespace System.ComponenModel.DataAnnotations. Considering our Post model, we can add validation specifying attributes like this:

public class Post

{

    public int Id { get; set; }

    public DateTime Date { get; set; }

    [Required]

    public string Title { get; set; }

    [Required]

    public string Body { get; set; }

}

In this example, we added the attribute Required to Title and Body to specify that a Post must always have a Title and a Body.

ModelState

These attributes affect the ModelState property of the Controller class.

public HttpResponseMessage Post(Post post)

{

    if (ModelState.IsValid)

    {

        // ...normal execution...

    }

    else

    {

        return new HttpResponseMessage(HttpStatusCode.BadRequest);

    }

}

The ModelState object is a Dictionary that contains a list of errors that can be used to check the model if contains errors.

With the Post model decorated as before, if we issue a post that breaks the required attributes, the ModelState will contain the list of errors and the property IsValid is set to false.

For example, if we post a Post without the body attribute, the ModelState will be something like this:

The ModelState is invalid

It contains the list of Keys and Values that do not pass the validation. The errors are a list of ModelErrors that contains the error messages and other information. We can use the error messages to build a response so that the client will know which attributes do not match the validation. In the case of a validation error, we should return an HTTP Status 400 Bad request.

The following table shows the actual built-in attributes:

Current built-in validation attributes

Attribute

Description

CompareAttribute

Provides an attribute that compares two properties.

CustomValidationAttribute

Specifies a custom validation method that is used to validate a property or class instance.

DataTypeAttribute

Specifies the name of an additional type to associate with a data field.

MaxLengthAttribute

Specifies the maximum length of array or string data allowed in a property.

MinLengthAttribute

Specifies the minimum length of array or string data allowed in a property.

RangeAttribute

Specifies the numeric range constraints for the value of a data field.

RegularExpressionAttribute

Specifies that a data field value in ASP.NET Dynamic Data must match the specified regular expression.

RequiredAttribute

Specifies that a data field value is required.

StringLengthAttribute

Specifies the minimum and maximum length of characters that are allowed in a data field.

This is the basic list of validators that inherit from ValidationAttribute. With the advent of .NET Framework 4.0, others were added as DataValidator, a subclass of ValidationAttribute that is used to derive a sort of type validator. These are listed in the following table:

DataType attributes

Attribute

Description

CreditCardAttribute

Specifies that a data field value is a credit card number.

EmailAddressAttribute

Validates an email address.

EnumDataTypeAttribute

Enables a .NET Framework enumeration to be mapped to a data column.

FileExtensionsAttribute

Validates file name extensions.

PhoneAttribute

Specifies that a data field value is a well-formed phone number using a regular expression for phone numbers.

UrlAttribute

Provides URL validation.

The attributes can be customized and personalized by deriving from the existing ones, or we can build new attributes that contain strong logic to validate the data. The base class from which we must derive is ValidationAttribute.

Summary

In this chapter, we saw how to use the validation mechanism to validate our models without modifying the existing code. This is just another tool to keep in our library.

Scroll To Top
Disclaimer
DISCLAIMER: Web reader is currently in beta. Please report any issues through our support system. PDF and Kindle format files are also available for download.

Previous

Next



You are one step away from downloading ebooks from the Succinctly® series premier collection!
A confirmation has been sent to your email address. Please check and confirm your email subscription to complete the download.