How To Validate MVC Model Using DataAnnotation Attribute

This tutorial helps you to understand how you can use DataAnnotation attributes for validation of model data.

DataAnnotation namespace

All DataAnnotation attributes are included in System.ComponentModel.DataAnnotations namespace. Various DataAnnotation attributes gives you a simple way to perform validation on model data. These attributes are helpful for common validation pattern like Required, Range, StringLength etc. It can perform validation on both client and server side.


Data Annotation Validator Attributes

  1. DataType

    Validates for particular data type e.g. value should be numeric only.
  2. DisplayName

    Specifies Display Name on View of property.
  3. DisplayFormat

    Specifies Display Format of property value e.g. Date value should be in yyyy-MM-dd format.
  4. Required

    Value must be provided to the model property.
  5. Range

    Data should be in specific range like Customer Age should be between 20 and 40.
  6. StringLength

    You can specify minimum and maximum length of property value.
  7. MaxLength

    You can specify only maximum length of property value.
  8. ReqularExpression

    Value should match regular expression e.g. email, phone, url etc.
  9. Bind

    specify fields to include or exclude for model binding.
  10. ScaffoldColumn

    It is a boolean property, specifies if the value should be hidden on view.
  11. EnumDataType

    Value should match with one of the enum member.

Use DataAnnotation attributes for model validation


Create MVC application with Model

Open your visual studio and create new empty ASP.NET MVC application. Follow ASP.NET MVC Model binding tutorial which gives you a basic mvc application with simple model binding.


Add DataAnnotation validation attributes

You can also Download source code of previous step for basic application.

In this step you will add DataAnnotation attributes to Customer model. Open the Customer.cs file from Models folder.

The DataAnnotation validation attributes belongs to System.ComponentModel.DataAnnotations so add reference of System.ComponentModel.DataAnnotations in Customer model.

You can decorate any property of Customer model with validation attributes describes earlier in this tutorial.

Replace the code from Customer model with below attributes and properties.

                
using System.ComponentModel.DataAnnotations;  

namespace FirstMVC.Models
{
    public class Customer
    {
        [Required(ErrorMessage="Customer ID is required")]        
        public string CustomerID { get; set; }

        [StringLength(10, ErrorMessage = "Company Name should
                        be less than or equal to five characters.")]        
        public string CompanyName { get; set; }

        [Range(20,40, ErrorMessage="Customer Age 
                        should be in 20 to 40 range." )]   
        public int Age { get; set; }

        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", 
                        ApplyFormatInEditMode = true)]
        public DateTime JoinDate { get; set; }
        
        [DataType(DataType.EmailAddress,ErrorMessage="Email is not valid." )]  
        [RegularExpression(@"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.
                            \w+([-.]\w+)*$",ErrorMessage="Email is not valid.")]  
        public string Email { get; set; }        
        
        [EnumDataType
            (typeof(EnumCustomerType))]  
        public EnumCustomerType CustomerType { get; set; }
    }

    public enum EnumCustomerType
    {
        New = 0,
        Regular = 1,
        Elite = 2
    }
}
            

Here you have use Required for CustomerID, StringLength for CompanyName, Range for Age, DataType for JoinDate, RegularExpression for Email and EnumDataType for CustomerType validation and provided ErrorMessage for each validation attribute.


CustomerDetails Action Method

In this step you will change the implementation of CustomerDetails action method of HomeController for setting values to Customer model. Check for more details on ASP.NET MVC Controller, Action method and ActionResult.

Open HomeController file from Controllers folder. Replace the code for CustomerDetails GET action method as shown below.

                
public ActionResult CustomerDetails()
{
    Customer cust = new Customer();
    cust.CustomerID = "ALFKI";
    cust.CompanyName = "Alfreds Futterkiste";
    cust.Age = 20;
    cust.JoinDate = DateTime.Now.AddYears(-4);
    cust.Email = "abc@amail.com";
    cust.CustomerType = EnumCustomerType.New; 

    return View(cust);
}
            

CustomerDetails View with Validation

In this step you will implement the CustomerDetails View binded with Customer model.

The DataAnnotations validation attributes used with Customer model properties. Which will force validation on View. You can get more details on how ASP.NET MVC request life cycle works

Open CustomerDetails.cshtml file from Views -> Home folder. And replace it with below code.

                
<html>
<head>
<title>Customer Details - dotnetmentors.com</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" 
    href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"/>
    <style type="text/css">
        .field-validation-error
        {
            color: #ff0000;
        }
        
        .field-validation-valid
        {
            display: none;
        }
        
        .input-validation-error
        {
            border: 1px solid #ff0000;
            background-color: #ffeeee;
        }
        
        .validation-summary-errors
        {
            font-weight: bold;
            color: #ff0000;
        }
        
        .validation-summary-valid
        {
            display: none;
        }
    </style>
</head>
<body>
@model FirstMVC.Models.Customer
<div class="container">
    <h2>
        <a href="http://dotnetmentors.com">
            <img src="http://dotnetmentors.com/images/dotnetmentors.png" 
                        alt="dotnetmentors.com" /></a>
        Customer Details
    </h2>
    @using (Html.BeginForm("CustomerDetails", "home"))
    {                        
        <div>
            @Html.ValidationSummary("Please correct below errors")
        </div>
        <div class="form-group">
            <table>
                <tr>
                    <td>
                        @Html.Label("Customer ID:")
                    </td>
                    <td>
                        @Html.TextBoxFor(m => m.CustomerID)
                    </td>
                    <td>
                        @Html.ValidationMessageFor(m => m.CustomerID,"*")
                    </td>
                </tr>                    
                <tr>
                    <td>
                        @Html.Label("Company Name:")
                    </td>
                    <td>
                        @Html.TextBoxFor(m => m.CompanyName)
                    </td>
                    <td>
                        @Html.ValidationMessageFor(m => m.CompanyName,"*")
                    </td>
                </tr>                    
                <tr>
                    <td>
                        @Html.Label("Age:")
                    </td>
                    <td>
                        @Html.TextBoxFor(m => m.Age )
                    </td>
                    <td>
                        @Html.ValidationMessageFor(m => m.Age, "*")
                    </td>
                </tr>
                <tr>
                    <td>
                        @Html.Label("Join Date:")
                    </td>
                    <td>
                        @Html.TextBoxFor(m => m.JoinDate)
                    </td>
                    <td>
                        @Html.ValidationMessageFor(m => m.JoinDate, "*")
                    </td>
                </tr>                    
                <tr>
                    <td>
                        @Html.Label("Email:")
                    </td>
                    <td>
                        @Html.TextBoxFor(m => m.Email)
                    </td>
                    <td>
                        @Html.ValidationMessageFor(m => m.Email, "*")
                    </td>
                </tr>                    
                <tr>
                    <td>
                        @Html.Label("Customer Type:")
                    </td>
                    <td>
                        @Html.TextBoxFor(m => m.CustomerType)
                    </td>
                    <td>
                        @Html.ValidationMessageFor(m => m.CustomerType,"*")
                    </td>
                </tr>                    
                <tr>
                    <td>
                         
                    </td>
                    <td>
                        <button type="submit" class="btn btn-default">
                            Submit</button>
                    </td>
                </tr>
            </table>
        </div>
            
    }
</div>
<script src="https://ajax.googleapis.com/ajax/libs/
                jquery/1.11.1/jquery.min.js" type="text/javascript"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"
            type="text/javascript"></script>
</body>
</html>    
                    
    

Now your View with validation is ready. Run the application and browse to http://localhost:52937/home/CustomerDetails. Enter invalid data for all fields and click Submit button. You will see below output.

ASP.NET MVC DataAnnotation Validation Attribute


Client side Model Validation in MVC

In this step you will learn how to do client side mvc model validation?

When you hit Submit button on CustomerDetails page it is validation the validation as written in customer model however it is doing at server side.

Open HomeController and add a breakpoint to CustomerDetails Post method.

ASP.NET MVC Post Action Method

Run your application and browse to http://localhost:52937/home/CustomerDetails. Enter some invalid values to all fields and click on Submit button. You will see the breakpoint gets hit as validations are happening on server side and there are no client side validations.

For client side validation you will have to add jquery.validate.min.js and jquery.validate.unobtrusive.js to your view. Open CustomerDetails.cshtml view and add below script files.

                
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/
                jquery.validate.min.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/mvc/4.0/
                jquery.validate.unobtrusive.js" type="text/javascript"></script>  
                    
            

Now run application and browse to http://localhost:52937/home/CustomerDetails. As you have implemented client side validations, the moment you entered invalid value it will show you error on page.

Download source code

Speak your mind :
Leave a comment for this article on dotnetbloogers.com
User profile picture on dotnetmentors.com

by Kamlesh at 9/17/2015 10:27:00 AM
If set model property value using JQUERY and when submit the page, I dont get value in post.. it should model property as null? Model is model => model.ProgramName value I am setting up Kamlesh Gujarathi
post comment on dotnetmentors.com
User profile picture on dotnetmentors.com

by Laxmikant at 9/29/2015 6:30:00 PM
@kamlesh, Try using jQuery AJAX POST call to action method. For more details go through http://dotnetmentors.com/mvc/jquery-ajax-call-with-jsonresult-in-asp-net-mvc.aspx
post comment on dotnetmentors.com
User profile picture on dotnetmentors.com

by yuvika at 10/30/2015 6:16:00 AM
EnumDatatype does not work for me other validation errors are shown perfectly
post comment on dotnetmentors.com
User profile picture on dotnetmentors.com

by Laxmikant at 10/30/2015 5:33:00 PM
@yuvika, what is the issue you are getting for Enum type validation? have you tried with downloading source code?
post comment on dotnetmentors.com