Validation is a key part of any web application we build. Building web applications with Asp .Net MVC Framework has a lot of benefits and one of them is validation using DataAnnotation.
In this blog post we will go through the basics of DataAnnotaiton and see how this can make our life easier while working with data validations. DataAnnotaiton works with other two components to provide us a robust client side validation. These components are
Following are some of the attributes available out of the box in System.ComponentModel.DataAnnotations Namespace.
- Required
- Compare
- Display
- Range
The [Required] DataAnnotation Attribute
This is the most commonly used and easiest to understand attribute of all. As the name suggests, when you want to make an input field required just decorate that Property in your C# class with [Required] attribute and everything else will be done auto-magically.
To continue reading further you will need the a basic MVC 4 application. If you are new to MVC 4 and not sure from where to start please refer to this blog post. It describes a step by step process to create an empty Asp .Net MVC application.
Once you follow along that post you should have a pretty clean Asp .Net MVC application built from scratch. Now, let's go ahead and add a new Controller AssetController. To examine the DataAnnotation we will be creating an imaginary Asset Management Application and the screen to enter Asset details.