TOC

The community is working on translating this tutorial into Romanian, but it seems that no one has started the translation process for this article yet. If you can help us, then please click "More info".

Models:

Types of Model Validation DataAnnotations

In the last article, we introduced Model Validation and showed you how easy it is to get started with. We used a couple of the validation-related DataAnnotations, like [Required] and [StringLength], but as mentioned, there are several other types. In this article, I will run through all of them, to give you a better idea of all the possibilities.

[Required]

Specifies that a value needs to be provided for this property. You should be aware that non-nullable value types (e.g. integers and DateTime's) are always required and therefore you don't need to add the [Required] attribute for them. For strings you should have in mind that an empty value will be treated like a NULL value and therefore result in a validation error. This behavior can be changed by using the AllowEmptyStrings property though:

[Required(AllowEmptyStrings = true)]

[StringLength]

Allows you to specify at least a maximum amount of characters (the first, non-optional parameter) for a string, with the added possibility of specifying a minimum amount as well. Here's an example:

[StringLength(50, MinimumLength = 3)]

In this case, the value can't be validated if it's less than 3 characters or more than 50 characters long.

[Range]

With the [Range] attribute, you can specify a minimum and a maximum value for a numeric property (int, float, double etc.). Both a minimum and a maximum is required when you use this attribute - like this:

[Range(1, 100)]

Now your numeric value must be between 1 and 100.

[Compare]

The [Compare] attribute allows you to set up a comparison between the property in question and another property, requiring them to match. A common use case for this could be to ensure that the user enters the same values in both the "Email" and the "EmailRepeated" fields:

[Compare("MailAddressRepeated")]
public string MailAddress { get; set; }

public string MailAddressRepeated { get; set; }

Specific types

If your string falls into a specific category, e.g. a phone number, the ASP.NET MVC can supply you with basic validation out of the box. Here's a list of the types you can specify:

  • [CreditCard]: Validates that the property has a credit card format.
  • [EmailAddress]: Validates that the property has an e-mail format.
  • [Phone]: Validates that the property has a telephone number format.
  • [Url]: Validates that the property has a URL format.

Common for all of these is that they only provide a very basic validation. So for instance, the e-mail validation will only ensure that the entered value will contain some of the characteristics of an e-mail address, like containing an @ character and so on, but it will still be possible to enter something that is not actually an e-mail address. For more accuracy and/or flexibility, use the [RegularExpression] attribute, or implement your own, custom logic, as described in one of the next articles.

[RegularExpression]

When none of the other types of validation are flexible enough, the last resort might very well be the [RegularExpression] attribute. It allows you to specify a Regular Expression which the value of your property will be validated against, and it will only be valid if there's a match. Regular Expressions are way too big a subject to handle in this article, but allow me to demonstrate just how powerful they are anyway. Imagine that your WebUser class has a MemberId which has to be in this specific format:

xx-0000-0000

Or in other words: Two letters, a dash and then two groups of four numbers with a dash between, like zx-1234-5678. We can make a Regular Expression for just that and put it inside our [RegularExpression] attribute:

[RegularExpression("[a-z]{2}-[0-9]{4}-[0-9]{4}")]
public string MemberId { get; set; }

The possibilities with Regular Expressions are almost endless, and they can be used in many other situations than just validation, so learning how to use them can be a good investment! Here's a couple of links if you want to get started learning Regular Expressions: Regex Tutorial & Cheat sheet / Regex Interactive Tutorial.

Summary

With a wide range of validation possibilities already built into the ASP.NET MVC framework, you can easily have most of your properties validated by adding a simple attribute to them. If you need more flexibility, you can always use the [RegularExpression] attribute or a custom implementation of validation logic, as we'll discuss in one of the next articles.


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!