Validation Attributes in ASP.Net MVC

asplogo-square

In this article I’m going to show you how to use some of the validation attributes provided by the asp.net MVC framework that can be used to validate your models and you’ll see by the end of this article how easy to use them and especially how much time you’re going to save comparing with the explicit model validation way.
Before we start, you need to know that all of these attributes are defined in the System.ComponentModel.DataAnnotations namespace, so make sure to import it before starting to use any validation attribute

Required Attribute

Use this validation attribute if you want to ensure that a data field has a value

    public class Student
    {
        [Required(AllowEmptyStrings = false, ErrorMessage = "The student first name is required")]
        public string FirstName { get; set; }
        [Required(AllowEmptyStrings = false, ErrorMessage = "The student last name is required")]
        public string LastName { get; set; }
    }

Compare Attribute

Use this validation attribute if you want to ensure that 2 properties of the same model have the same value

    public class Student
    {
        [Compare("ConfirmEmail",ErrorMessage = "Email value must be identical to the confirm email value")]
        public string Email { get; set; }
        [Compare("Email", ErrorMessage = "The confirm email value must be identical to the email value")]
        public string ConfirmEmail { get; set; }
    }

StringLength Attribute

Use this validation attribute to specify the minimum and maximum length of a data field

    public class Student
    {
        [Required(AllowEmptyStrings = false, ErrorMessage = "The student first name is required")]
        [StringLength(20, ErrorMessage = "The student first name value cannot exceed 20 characters.")]
        public string FirstName { get; set; }
        [Required(AllowEmptyStrings = false, ErrorMessage = "The student last name is required")]
        [StringLength(20, ErrorMessage = "The student last name value cannot exceed 20 characters.")]
        public string LastName { get; set; }
    }

Range Attribute

Use this attribute if you want to ensure that the value of a data field exists in a given range

    public class Student
    {
        [Range(typeof(DateTime), "1/1/1980", "1/1/1990",ErrorMessage = "Birth date must be between {1} and {2}")]
        public DateTime BirthDate { get; set; }
    }

RegularExpression Attribute

Use this attribute if you want to validate the value of a data field against a regular expression

    public class Student
    {
        [RegularExpression(@"^[a-zA-Z''-'\s]$", ErrorMessage = "Numbers and special characters are not allowed in the first name.")]
        public string FirstName { get; set; }
        [RegularExpression(@"^[a-zA-Z''-'\s]$", ErrorMessage = "Numbers and special characters are not allowed in the last name.")]
        public string LastName { get; set; }
    }

EmailAddress Attribute

validate if the value of a data field is a valid emmail address or not

    public class Student
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public DateTime BirthDate { get; set; }
        [EmailAddress(ErrorMessage = "Please enter a valid email address")]
        public string Email { get; set; }
        [EmailAddress(ErrorMessage = "Please enter a valid email address")]
        public string ConfirmEmail { get; set; }
    }

CreditCardAttribute Attribute

checks if the value of a given data field is a valid credit card number or not

    public class Student
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        [CreditCard(ErrorMessage = "Please enter a valid credit card number")]
        public string CreditCardNumber { get; set; }
    }

Phone Attribute

checks if the value of a given data field has a valid phone number format

    public class Student
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        [Phone(ErrorMessage = "Please enter a valid phone number")]
        public string PhoneNumber { get; set; }
    }

Url Attribute

checks if the value of a given data field has a valid URL format or not

    public class Student
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        [Url(ErrorMessage = "Please enter a valid website")]
        public string Website { get; set; }
    }

MinLength Attribute

Ensure that the value of a given data field has a minimum length (characters number)

    public class Student
    {
        [MinLength(3, ErrorMessage = "The first name value must contains at least 3 characters")]
        public string FirstName { get; set; }
        [MinLength(3, ErrorMessage = "The last name value must contains at least 3 characters")]
        public string LastName { get; set; }
    }

MaxLength Attribute

Ensure that the value of a given data field has a maximum length

   public class Student
    {
        [MaxLength(20, ErrorMessage = "The first name value must contains no more than 20 characters")]
        public string FirstName { get; set; }
        [MaxLength(20, ErrorMessage = "The last name value must contains no more than 20 characters")]
        public string LastName { get; set; }
    }

FileExtensions Attributes

Ensure that a file extension is valid by comparing it to the list of extensions listed in the Extensions property

    public class Student
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        [FileExtensions(Extensions = "png,jpg,jpeg,gif", ErrorMessage = "The image must be of these types: png,jpg,jpeg,gif")]
        public string ImagePath { get; set; }
    }

Summary

As you see, Asp.Net MVC provides a rich collection of validation attributes that let developers validate user input easily.
The awesomeness of Asp.net MVC framework doesn’t stop right here but instead it provides other mechanisms for user input validation and we’re going to see them in another articles ;).

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s