Validate form using Data Annotation in MVC3 Razor


  1. Data Annotations are attributes you can find in the System.ComponentModel.DataAnnotations namespace.
  2. Data Annotation attributes are used to validate the form's posted data.
  3. Data Annotations help us to define the rules to the model classes or properties for data validation and displaying suitable messages to end users.
  4. In this article we will see a simple example how to validate a form using Data Annotation attributes.
Watch Video

First we will create a simple Register form. To create a form we have used EditorForModel helper which renders the control for model properties.


View :

@model AttributesDemo.ViewModel.Register
@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
@if (ViewBag.Success != null)
{
    <h3>@ViewBag.Success</h3>
}

@using (Html.BeginForm())
{
    @Html.EditorForModel("Register")
    <br />
    <input type="submit" value="Submit" />
    <input type="reset" value="Reset" />
}

As mentioned earlier we have used EditorForModel helper to render our form. The model referenced here is Register. We have two buttons of type submit and reset.

Model :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace AttributesDemo.ViewModel
{
    public class Register
    {
        [Required(ErrorMessage="FirstName is Required")]
        public string FirstName { get; set; }

        public string LastName { get; set; }

        [Required(ErrorMessage = "Age is Required")]
        [Range(20,40,ErrorMessage="Age must be between 20 and 40")]
        public int Age { get; set; }

        [Required(ErrorMessage = "Email is Required")]
        [RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}",ErrorMessage="Not a valid format.")]
        public string Email { get; set; }

        [Required(ErrorMessage = "Password is Required")]
        [DataType(DataType.Password)]
        [StringLength(10,ErrorMessage="Password must be less than 10 letters")]
        public string Password { get; set; }

        [Required(ErrorMessage = "ConfirmPassword is Required")]
        [DataType(DataType.Password)]
        [StringLength(10, ErrorMessage = "Password must be less than 10 letters")]
        [Compare("Password",ErrorMessage="Password and Confirm Password do not match.")]
        public string ConfirmPassword { get; set; }

    }
}

The above is our model. We have included the System.ComponentModel.DataAnnotations reference. Without including this reference we cannot use Data Annotation attributes. We have six properties, which will be rendered on form. We have applied various Data Annotation attributes on properties. These validation attributes will work when form is posted and validates the user input.

Controller :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AttributesDemo.ViewModel;

namespace AttributesDemo.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(Register registerDetails)
        {
            if (ModelState.IsValid)
            {
                ViewBag.Success = "User Successfully Registered !!";
                return View();
            }
            else
            {
                return View("Index", registerDetails);
            }
        }

    }
}

The above is the controller class. The Index ActionResult method renders the form on the view with Data Annotation attributes applied on the properties of model. the form is posted to the second Index ActionResult method. This method accepts a parameter of type Register class which is our model. This object has the reponse filled in properties provided by the user. 
Further we check the model state, if the validation for all the properties are successfull then the model state is valid and we return success message and if the validation fails for any property then the model state is invalid and we return thr model object with error message to the view. The error messages are displayed on UI, when the model state is not valid.

To check how each Data Annotation attribute works and validates visit :


link


Screenshots :






2 comments: