Skip to main content

MVC Data Annotations for Model Validation

MVC Data Annotations for Model Validation

 
Data validation is a key aspect for developing web application. In Asp.net MVC, we can easily apply validation to web application by using Data Annotation attribute classes to model class. Data Annotation attribute classes are present in System.ComponentModel.DataAnnotations namespace and are availlable to Asp.net projects like Asp.net web application & website, Asp.net MVC, Web forms and also to Entity framework orm models.
Data Annotations help us to define the rules to the model classes or properties for data validation and displaying suitable messages to end users.

Data Annotation Validator Attributes

  1. DataType

    Specify the datatype of a property
  2. DisplayName

    specify the display name for a property.
  3. DisplayFormat

    specify the display format for a property like different format for Date proerty.
  4. Required

    Specify a property as required.
  5. ReqularExpression

    validate the value of a property by specified regular expression pattern.
  6. Range

    validate the value of a property with in a specified range of values.
  7. StringLength

    specify min and max length for a string property.
  8. MaxLength

    specify max length for a string property.
  9. Bind

    specify fields to include or exclude when adding parameter or form values to model properties.
  10. ScaffoldColumn

    specify fields for hiding from editor forms.

Designing the model with Data Annotations

  1. using System.ComponentModel;
  2. using System.ComponentModel.DataAnnotations;
  3. using System.Web.Mvc;
  4. namespace Employee.Models
  5. {
  6. [Bind(Exclude = "EmpId")]
  7. public class Employee
  8. {
  9. [ScaffoldColumn(false)]
  10. public int EmpId { get; set; }
  11. [DisplayName("Employee Name")]
  12. [Required(ErrorMessage = "Employee Name is required")]
  13. [StringLength(100,MinimumLength=3)]
  14. public String EmpName { get; set; }
  15. [Required(ErrorMessage = "Employee Address is required")]
  16. [StringLength(300)]
  17. public string Address { get; set; }
  18. [Required(ErrorMessage = "Salary is required")]
  19. [Range(3000, 10000000,ErrorMessage = "Salary must be between 3000 and 10000000")]
  20. public int Salary{ get; set; }
  21. [Required(ErrorMessage = "Please enter your email address")]
  22. [DataType(DataType.EmailAddress)]
  23. [Display(Name = "Email address")]
  24. [MaxLength(50)]
  25. [RegularExpression(@"[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}", ErrorMessage = "Please enter correct email")]
  26. public string Email { get; set; }
  27. }
  28. }
Once we have define validation to the model by using data annotations, these are automatically used by Html Helpers in views. For client side validation to work, please ensure that below two <SCRIPT> tag references are in the view.
  1. <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
  2. <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

Presenting the model in the view

  1. @model Employee.Models
  2. @{
  3. ViewBag.Title = "Employee Details";
  4. Layout = "~/Views/Shared/_Layout.cshtml";
  5. }
  6. @using (Html.BeginForm())
  7. {
  8. <div class="editor-label">
  9. @Html.LabelFor(m => m.EmpName)
  10. </div>
  11. <div class="editor-field">
  12. @Html.TextBoxFor(m => m.EmpName)
  13. @Html.ValidationMessageFor(m => m.EmpName)
  14. </div>
  15. <div class="editor-label">
  16. @Html.LabelFor(m => m.Address)
  17. </div>
  18. <div class="editor-field">
  19. @Html.TextBoxFor(m => m.Address)
  20. @Html.ValidationMessageFor(m => m.Address)
  21. </div>
  22. <div class="editor-label">
  23. @Html.LabelFor(m => m.Salary)
  24. </div>
  25. <div class="editor-field">
  26. @Html.TextBoxFor(m => m.Salary)
  27. @Html.ValidationMessageFor(m => m.Salary)
  28. </div>
  29. <div class="editor-label">
  30. @Html.LabelFor(m => m.Email)
  31. </div>
  32. <div class="editor-field">
  33. @Html.TextBoxFor(m => m.Email)
  34. @Html.ValidationMessageFor(m => m.Email)
  35. </div>
  36. <p> <input type="submit" value="Save" />
  37. </p>
  38. }

Comments

Popular posts from this blog

What is cookie? Advantages and disadvantages of cookies?

What is cookie? A cookie is a small piece of text file stored on user's computer in the form of name-value pair. Cookies are used by websites to keep track of visitors e.g. to keep user information like username etc. If any web application using cookies, Server send cookies and client browser will store it. The browser then returns the cookie to the server at the next time the page is requested. The most common example of using a cookie is to store User information, User preferences, Password Remember Option etc.It is also one of the common and mostly asked interview questions. Some facts about Cookie Here are a few facts to know about cookies: · Cookies are domain specific i.e. a domain cannot read or write to a cookie created by another domain. This is done by the browser for security purpose. · Cookies are browser specific. Each browser stores the cookies in a different location. The cookies are browser specific and so a cookie created in one browser(e.g in Google Chrome...

Code First Getting Started

In this tutorial let us create a simple application to demonstrate the use of entity framework using code first. We are using Visual Studio 2015 and entity framework 6.1.3. You can download Visual Studio community Edition . You should have the basic knowledge of .Net framework, C# and MS SQL Server. In this tutorial, we will create a simple application with a user class.  Our user class will have basic information like name and email address of the user. Create the Project Open Visual Studio. File ->New -> Project Select C# -> Select Console Application Name the application as “EFGettingStarted” Click on OK Install Entity Framework The next step is to install the Entity framework. This can be installed via nuget package console. Click on Tools->Nuget Package manager -> Package Manager Console and type the following command C# 1 2 3   install - package entityframework   This will in...

Top 10 ASP.NET Web API Interview Questions

What is ASP.NET Web API? ASP.NET Web API is a framework that simplifies building HTTP services for broader range of clients (including browsers as well as mobile devices) on top of .NET Framework. Using ASP.NET Web API, we can create non-SOAP based services like plain XML or JSON strings, etc. with many other advantages including: Create resource-oriented services using the full features of HTTP Exposing services to a variety of clients easily like browsers or mobile devices, etc. What are the Advantages of Using ASP.NET Web API? Using ASP.NET Web API has a number of advantages, but core of the advantages are: It works the HTTP way using standard HTTP verbs like  GET ,  POST ,  PUT ,  DELETE , etc. for all CRUD operations Complete support for routing Response generated in JSON or XML format using  MediaTypeFormatter It has the ability to be hosted in IIS as well as self-host outside of IIS Supports Model binding and Validation Support for OD...