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 give you a simple way to perform validation on model data. These attributes are helpful for common validation patterns like Required, Range, StringLength, etc. It can perform validation on both the client and server side.

Data Annotation Validator Attributes

  1. DataType

    Validates for particular data types 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

    The 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 the minimum and maximum length of property value.
  7. MaxLength

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

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

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

    It is a boolean property, specifies if the value should be hidden in view.
  11. EnumDataType The value should match with one of the enum members.

Use DataAnnotation attributes for model validation

Create a MVC application with Model

Open your visual studio and create a 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 the Customer model. Open the Customer.cs file from the 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 the Customer model with validation attributes describes earlier in this tutorial.

Replace code from Customer model with the 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="https://geeksarray.com">
            <img src="https://geeksarray.com/images/geeksarray.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 the 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="https://cdnjs.cloudflare.com/ajax/libs/
    jquery-validate/1.19.2/jquery.validate.min.js"
    type="text/javascript"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/
    jquery-validation-unobtrusive/3.2.11/jquery.validate.unobtrusive.min.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.

Source code on Git hub Source Code on Github

Speak your mind
Please login to post your comment!


  • geeksarray user
    09/17/2015 10:27 AM Kamlesh

    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

  • geeksarray user
    09/29/2015 06:30 PM Laxmikant

    @kamlesh, Try using jQuery AJAX POST call to action method. For more details go through https://geeksarray.com/blog/jquery-ajax-call-with-jsonresult-in-asp-net-mvc

  • geeksarray user
    10/30/2015 06:16 AM yuvika

    EnumDatatype does not work for me other validation errors are shown perfectly

  • geeksarray user
    10/30/2015 05:33 PM Laxmikant

    @yuvika, what is the issue you are getting for Enum type validation? have you tried with downloading source code?