Validate Form using Data Annotation in MVC

Sourav.Kayal
Posted by in ASP.NET MVC category on for Beginner level | Points: 250 | Views : 3084 red flag

How to validate html form using data annotation technique

Validate form using Data Annotation in MVC

In this article we will learn how to validate form using data annotation technique in MVC application. As we know form variation is very important part of any application and there are various techniques to validate form.

In MVC application data annotation is one of them.

Create Model class

To implement data annotation method we will create one simple model class called Person. In person class there are three attributes, those are PersonName , surname and Age. Now, we are interested to validate those three properties.  Our validation condition is in below.

PersonName:- Person Name is required.

Surname: - Surname is required

Age:- Age is required and it should be more than 18.

using System;
using System.ComponentModel.DataAnnotations;
namespace PersonModel
{
    public class Person
    {
        [Required(ErrorMessage = "Enter Person Name")]
        public String PersonName { get; set;}
 
        [Required(ErrorMessage = "Enter Person Surname")]
        public String Surname { get; set;}
 
        [Required(ErrorMessage = "Enter Age")]
        [Range(18, 60, ErrorMessage="Age should more than 18")]
        public int Age { get; set; }
    }
}
 

To validate each and every property we have to set appropriate attribute on each of them.

 

Create controller class

Now, we will create controller class to call appropriate view.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
 namespace MVCTest.Controllers
{
    public class PersonController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult GetPerson(PersonModel.Person P)
        {
            if (!ModelState.IsValid)
            {
return View("Index");
            }
            else                return Content("Valid User" + "Name:-" + P.PersonName + "Surname:- " + P.Surname +" Age:- " + P.Age) ;
        }
 
    }
}

In controller class, there are two actions. Index action is the default action in this application. When we will run this application by default Index() action will get call.

GetPerson() action will call when we will submit form. Within GetPerson() action we are checking State of model class using IsValid property.

If user’s input validate model’s condition then it will show user’s input otherwise it will return same view.

Create html form in View

Now, we will create a simple HTML form in view. Have a look on below code.

@model PersonModel.Person
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <title>Index</title>
</head>
<body>
    <div>
        @using (Html.BeginForm("GetPerson", "Person",FormMethod.Post))
        {
            @Html.ValidationSummary(true)
            <p>
                @Html.LabelFor(m => m.PersonName)
                @Html.TextBoxFor(m => m.PersonName)
                @Html.ValidationMessageFor(m=>m.PersonName)
            </p>
            <p>
                @Html.LabelFor(m=>m.Surname)
                @Html.TextBoxFor(m => m.Surname,"Surname")
                @Html.ValidationMessageFor(m => m.Surname)
            </p>
            <p>
                @Html.LabelFor(m=> m.Age)
                @Html.TextBoxFor(m=>m.Age,"Age")
                @Html.ValidationMessageFor(m=> m.Age)
            </p>
            <input type="submit" value="Subit" />
        }
    </div>
</body>
</html>
 

Here we have used HTML helper class to implement HTML form.

Output:-


Conclusion:-

In this article we have learned how to validate HTML form using data annotation technique. Though there are various validation techniques in web application, Data annotation is very useful and very popular in MVC application.

Page copy protected against web site content infringement by Copyscape

About the Author

Sourav.Kayal
Full Name: Sourav Kayal
Member Level: Silver
Member Status: Member,MVP
Member Since: 6/20/2013 2:09:01 AM
Country: India
Read my blog here http://ctrlcvprogrammer.blogspot.in/
http://www.dotnetfunda.com
I am .NET developer working for HelixDNA Technologies,Bangalore in healthcare domain. Like to learn new technology and programming language. Currently working in ASP.NET ,C# and other microsoft technologies.

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)