Data Annotations Validation in ASP.NET 4.5

This article explains how to use data annotations for validation in ASP.Net 4.5. So, let's proceed with the following procedure:

  • Create a Registration Page.
  • Create DataAnnotationsValidation.Models (Validation.cs).
  • The effect of a custom validation message: Required, String Length, Data Type, Range, Compare and Regular Expression.

Creating a Registration Page

Create a new project using "File" -> "New" -> "Project..." then select web "ASP.NET Web Forms Application". Name it "DataAnnotationsValidation".



Now, seelct New ASP.NET Project then select the template Empty and select Web Forms then click OK.



Next, create the code-behind as follows, displaying the validation errors to the users in the Registration.aspx.

Registration.aspx 

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Registration.aspx.cs" Inherits="DataAnnotationsValidation.Registration" %>  
  2.   
  3. <!DOCTYPE html>  
  4.   
  5. <html xmlns="http://www.w3.org/1999/xhtml">  
  6. <head runat="server">  
  7.     <title>Employees Registration</title>  
  8.     <link href="Content/bootstrap.min.css" rel="stylesheet" />  
  9. </head>  
  10. <body>  
  11.     <form id="form1" runat="server">  
  12.         <div class="container">  
  13.   
  14.             <div class="well">  
  15.   
  16.                 <h1>Data Annotations  Validation in ASP .NET 4.5 </h1>  
  17.             </div>  
  18.             <div class=" panel panel-default">  
  19.                 <div class="panel-heading">  
  20.                     <h3 class="panel-title">Employees Registration</h3>  
  21.   
  22.                 </div>  
  23.                 <div class="panel-body">  
  24.                     <div class="text-center">  
  25.                     <asp:ValidationSummary ID="validationSummary" runat="server" ShowModelStateErrors="true" DisplayMode="List" ForeColor="Red"  />  
  26.                     </div>  
  27.                         <div class="col-md-8">  
  28.                             <div class="form-group col-lg-12">  
  29.                                 <label>First Name</label>  
  30.                                 <asp:TextBox ID="FirstName" runat="server" class="form-control"></asp:TextBox>  
  31.                             </div>  
  32.                             <div class="form-group col-lg-12">  
  33.                                 <label>Last Name</label>  
  34.                                 <asp:TextBox ID="LastName" runat="server" class="form-control"></asp:TextBox>  
  35.                             </div>  
  36.                             <div class="form-group col-lg-12">  
  37.                                 <label>User ID</label>  
  38.                                 <asp:TextBox ID="UserID" runat="server" class="form-control"></asp:TextBox>  
  39.                             </div>  
  40.                             <div class="form-group col-lg-6">  
  41.                                 <label>Password </label>  
  42.   
  43.                                 <asp:TextBox ID="Password" runat="server" class="form-control"></asp:TextBox>  
  44.                             </div>  
  45.                             <div class="form-group col-lg-6">  
  46.                                 <label>Password Confirm </label>  
  47.   
  48.                                 <asp:TextBox ID="PasswordConfirm" runat="server" class="form-control"></asp:TextBox>  
  49.                             </div>  
  50.                             <div class="form-group col-lg-6">  
  51.                                 <label>Mobile </label>  
  52.                                 <asp:TextBox ID="Mobile" runat="server" class="form-control"></asp:TextBox>  
  53.                             </div>  
  54.                             <div class="form-group col-lg-6">  
  55.                                 <label>Age </label>  
  56.                                 <asp:TextBox ID="Age" runat="server" class="form-control"></asp:TextBox>  
  57.                             </div>                              
  58.                             <div class="form-group col-lg-6">  
  59.                                 <label>Email </label>  
  60.                                 <asp:TextBox ID="Email" runat="server" class="form-control"></asp:TextBox>  
  61.                             </div>  
  62.                             <div class="form-group col-lg-6">  
  63.                                 <label>Email Confirm </label>  
  64.                                 <asp:TextBox ID="EmailConfirm" runat="server" class="form-control"></asp:TextBox>  
  65.                             </div>  
  66.                             <div class="form-group col-lg-6">  
  67.                                 <label>DOB </label>  
  68.                                 <asp:TextBox ID="Date" runat="server" class="form-control"></asp:TextBox>  
  69.                             </div>  
  70.                             <div class="form-group col-lg-6">  
  71.                                 <label>Salary </label>  
  72.                                 <asp:TextBox ID="Total" runat="server" class="form-control"></asp:TextBox>  
  73.                             </div>  
  74.                             <div class="form-group col-lg-6">  
  75.                                 <label>City </label>  
  76.                                 <asp:TextBox ID="HomeCity" runat="server" class="form-control"></asp:TextBox>  
  77.                             </div>  
  78.                             <div class="form-group col-lg-6">  
  79.                                 <label>Department </label>  
  80.                                   
  81.                                 <asp:DropDownList ID="Department" runat="server" class="form-control">  
  82.                         <asp:ListItem Value="">Choose an Option</asp:ListItem>  
  83.                         <asp:ListItem Value="HR">HR</asp:ListItem>  
  84.                         <asp:ListItem Value="Account">Account</asp:ListItem>  
  85.                                     </asp:DropDownList>  
  86.                             </div>  
  87.                             <div class="form-group col-lg-6">  
  88.                                 <asp:Button ID="btnsubmit" runat="server" Text="submit" />  
  89.                             </div>  
  90.                         </div>                      
  91.                 </div>  
  92.                 </div>  
  93.             </div>  
  94.     </form>  
  95. </body>  
  96. </html>  
Create DataAnnotationsValidation.Models for Validation 

Now, do something with Models then click Add -> Class.

Now, do something with Add New Item then select Class then provide Validation.cs for the name then click on Add.



Applying validation attributes to the Validation class

Validation.cs 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. //using Namespace  
  7. using System.ComponentModel.DataAnnotations;  
  8.   
  9.   
  10. namespace DataAnnotationsValidation.Models  
  11. {  
  12.     public class Validation  
  13.     {          
  14.   
  15.         [Required]  
  16.         [StringLength(120, MinimumLength = 3)]  
  17.         public string FirstName { getset; }  
  18.   
  19.         [Required]  
  20.         [StringLength(120, MinimumLength = 3)]  
  21.         public string LastName { getset; }  
  22.   
  23.         [Required]  
  24.         [StringLength(25, MinimumLength = 3)]  
  25.         public string UserID { getset; }  
  26.   
  27.         [Required]  
  28.         [DataType(DataType.Password)]  
  29.         public string Password { getset; }  
  30.   
  31.         [Required]  
  32.         [Compare("Password")]  
  33.         public string PasswordConfirm { getset; }  
  34.   
  35.         [Required]  
  36.         [Range(18, 100, ErrorMessage = "Please enter an age between 18 and 50")]  
  37.         public int Age { getset; }  
  38.   
  39.         [Required]         
  40.         [StringLength(10)]  
  41.         public int Mobile { getset; }          
  42.   
  43.         [RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}", ErrorMessage = "Email doesn't look like a valid email address.")]  
  44.         public string Email { getset; }  
  45.   
  46.         [Compare("Email")]  
  47.         public string EmailConfirm { getset; }  
  48.   
  49.         [Range(typeof(decimal), "0.00""15000.00")]  
  50.         public decimal Total { getset; }  
  51.   
  52.         [Required]  
  53.         [DataType(DataType.Date)]  
  54.         public DateTime Date { getset; }  
  55.   
  56.         [Required]  
  57.         public string HomeCity { getset; }  
  58.   
  59.         [Required]  
  60.         public string Department { getset; }  
  61.   
  62.     }  
  63. }  
Next, create the code-behind as follows.
 
Registration.aspx.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7.   
  8. //using Namespace Models  
  9. using System.Web.ModelBinding;  
  10. using DataAnnotationsValidation.Models;  
  11.   
  12. namespace DataAnnotationsValidation  
  13. {  
  14.     public partial class Registration : System.Web.UI.Page  
  15.     {  
  16.         protected void Page_Load(object sender, EventArgs e)  
  17.         {  
  18.             if (IsPostBack)  
  19.             {  
  20.                 Validation v = new Validation();  
  21.                 if (TryUpdateModel(v, new FormValueProvider(ModelBindingExecutionContext)))  
  22.                 {  
  23.                     ShowMessage(v.ToString());                      
  24.                 }  
  25.             }  
  26.         }  
  27.         /// <summary>  
  28.         /// This function is used for show message.  
  29.         /// </summary>  
  30.         /// <param name="msg"></param>  
  31.         void ShowMessage(string msg)  
  32.         {  
  33.             ClientScript.RegisterStartupScript(Page.GetType(), "validation""<script language='javascript'>alert('" + msg + "');</script>");  
  34.         }  
  35.   
  36.     }  
  37. }  
Now run the page, it will look like the following to use validation to check the input. 

employee registration

Now run the page, it will display validation error messages.

Now, the error messages are shown in the validation summary.

Now, a custom validation message is displaying the validation error messages.


I hope this article is useful. If you have any other questions then please provide your comments.


Similar Articles