Validation In ASP.NET Web Form

Let's create a Web application first to implement validation controls in ASP.NET, and then do the server-side validation.

using System.ComponentModel.DataAnnotations,

 

Add New web page in your application; here I have added "Register.aspx." Add the following html in your "Register.aspx" page. 

  1. <div>  
  2.              
  3.            <asp:TextBox ID="txtName" placeholder="Enter Full Name" runat="server"></asp:TextBox>  
  4.   
  5.            <br />  
  6.            <asp:TextBox ID="txtEmail" placeholder="Enter Email" runat="server"></asp:TextBox>  
  7.   
  8.            <br />  
  9.            <asp:TextBox ID="txtMobile" placeholder="Enter Mobile" runat="server"></asp:TextBox>  
  10.   
  11.            <br />  
  12.            <asp:TextBox ID="txtPassword" placeholder="Enter Password" runat="server"></asp:TextBox>  
  13.   
  14.            <br />  
  15.            <asp:TextBox ID="txtAge" placeholder="Enter Age" runat="server"></asp:TextBox>  
  16.   
  17.            <br />  
  18.   
  19.            <asp:Button ID="btnSubmit" runat="server" Text="Submit"  
  20.                OnClick="btnSubmit_Click" />  
  21.        </div>  

Apply validation for the following fields:

 
Drag and drop Validation controls from toolbar:
 
 
  
 
Copy paste the following code where I have map validation control with other controls, such as textboxes:
  1. <div>  
  2.            Full Name :<asp:TextBox ID="txtName" placeholder="Enter Full Name" runat="server"></asp:TextBox>  
  3.   
  4.            <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Name cannot be blank" ControlToValidate="txtName" ForeColor="Red"></asp:RequiredFieldValidator>  
  5.   
  6.            <br />  
  7.            Email :<asp:TextBox ID="txtEmail" placeholder="Enter Email" runat="server"></asp:TextBox>  
  8.   
  9.            <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Email cannot be blank" ControlToValidate="txtEmail" ForeColor="Red"></asp:RequiredFieldValidator>  
  10.   
  11.            <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="txtEmail" ErrorMessage="Enter proper email format" ForeColor="Red" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>  
  12.   
  13.            <br />  
  14.            Mobile :<asp:TextBox ID="txtMobile" placeholder="Enter Mobile" runat="server"></asp:TextBox>  
  15.            <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="Mobile cannot be blank" ControlToValidate="txtMobile" ForeColor="Red"></asp:RequiredFieldValidator>  
  16.            <asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server" ControlToValidate="txtMobile" ErrorMessage="Mobile number must be 10 digit" ForeColor="Red" ValidationExpression="\d{10}"></asp:RegularExpressionValidator>  
  17.            <br />  
  18.            Password :<asp:TextBox ID="txtPassword" placeholder="Enter Password" runat="server"></asp:TextBox>  
  19.            <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ErrorMessage="Password cannot be blank" ControlToValidate="txtPassword" ForeColor="Red"></asp:RequiredFieldValidator>  
  20.            <asp:CompareValidator ID="CompareValidator1" runat="server" ControlToCompare="txtPassword" ControlToValidate="txtConfirmPassword" ErrorMessage="Password and confiem password must be same" ForeColor="Red"></asp:CompareValidator>  
  21.            <br />  
  22.            Confirm Password :<asp:TextBox ID="txtConfirmPassword" placeholder="Confirm Password" runat="server"></asp:TextBox>  
  23.            <br />  
  24.            Age :<asp:TextBox ID="txtAge" placeholder="Enter Age" runat="server"></asp:TextBox>  
  25.            <asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ErrorMessage="Age cannot be blank" ControlToValidate="txtAge" ForeColor="Red"></asp:RequiredFieldValidator>  
  26.            <asp:RangeValidator ID="RangeValidator1" runat="server" ErrorMessage="Age must be between 18 to 40" ControlToValidate="txtAge" ForeColor="Red" MaximumValue="40" MinimumValue="18"></asp:RangeValidator>  
  27.            <br />  
  28.   
  29.            <asp:Button ID="btnSubmit" runat="server" Text="Submit"  
  30.                OnClick="btnSubmit_Click" />  
  31.        </div>  
Now run the application. Running the application will give you errors as in the following screenshot:

 
To resolve the issue, add the following line in web.config file:
  1. <appSettings>  
  2.    <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />  
  3.  </appSettings>  
Now, run the application and check all validations:
  • Click on the submit button and check whether all required field validation works properly.
  • Enter 8 digit and 10 digit in mobile textbox and check the Regular Expression Validation.
  • Check Regular Expression Validation for email.
  • Check Range Validation for age and compare validation for Password and Confirm Password.
  
 
Now all the Validations work properly.
 
Now, add Class Library in our project for implementing Validation through System.ComponentModel.DataAnnotations. For this follow the steps below:
 
Add New Project, then select Class Library and give name 'ClassLibrary1' and add class 'register.cs'
 
 
 
 
Create property for Name, Mobile, Email, Password, ConfirmPassword and Age field.
  1. public class register  
  2. {  
  3.     [Required(ErrorMessage = "Name is required")]  
  4.     public string name  
  5.     {  
  6.         get;  
  7.         set;  
  8.     }  
  9.   
  10.     [Required(ErrorMessage = "email is required")]  
  11.     [RegularExpression(@ "\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z",  
  12.         ErrorMessage = "Please enter proper email")]  
  13.     public string email   
  14.     {  
  15.         get;  
  16.         set;  
  17.     }  
  18.   
  19.     [Required(ErrorMessage = "Mobile is required")]  
  20.     [RegularExpression(@ "\d{10}", ErrorMessage = "Please enter 10 digit Mobile No.")]  
  21.     public string mobile  
  22.     {  
  23.         get;  
  24.         set;  
  25.     }  
  26.   
  27.     [Required(ErrorMessage = "Password is required")]  
  28.     [DataType(DataType.Password)]  
  29.     public string Password   
  30.     {  
  31.         get;  
  32.         set;  
  33.     }  
  34.   
  35.     [Required(ErrorMessage = "Confirm Password is required")]  
  36.     [DataType(DataType.Password)]  
  37.     [Compare("Password")]  
  38.     public string ConfirmPassword   
  39.     {  
  40.         get;  
  41.         set;  
  42.     }  
  43.   
  44.     [Required(ErrorMessage = "Age is required")]  
  45.     [Range(typeof(int), "18""40", ErrorMessage = "Age can only be between 18 and 40")]  
  46.     public string age  
  47.     {  
  48.         get;  
  49.         set;  
  50.     }  
  51. }  
Build the class library and add the reference 'ClassLibrary' in your Web Application.
 
 
 
Now add the following code on submit button click event; here we will do the server-side validation for all the properties using data annotations:
  1. protected void btnSubmit_Click(object sender, EventArgs e)  
  2.         {  
  3.             register reg = new register();  
  4.   
  5.             reg.name = txtName.Text.ToString();  
  6.             reg.email = txtEmail.Text.ToString();  
  7.             reg.mobile = txtMobile.Text.ToString();  
  8.             reg.Password = txtPassword.Text.ToString();  
  9.             reg.ConfirmPassword = txtConfirmPassword.ToString();  
  10.             reg.age = txtAge.Text.ToString();  
  11.   
  12.             var context = new ValidationContext(reg, serviceProvider: null, items: null);  
  13.             var results = new List<ValidationResult>();  
  14.             var isValid = Validator.TryValidateObject(reg, context, results, true);  
  15.   
  16.             if (!isValid)  
  17.             {  
  18.                 foreach (var validationResult in results)  
  19.                 {  
  20.                     Response.Write(validationResult.ErrorMessage.ToString());  
  21.                 }  
  22.   
  23.                 return;  
  24.             }  
  25.         }  
Here setting validateAllProperties = true is the important part. If it is false then it will perform only the first default validation 'Required' and it will not check other Validation for the properties like 'Regularexpression', 'Range', etc.
 
 

Now check the server-side validation and comment on all the validation controls in the register.aspx  page and run the application.
 
 
Check all the validations. So here, if in the browser we disable JavaScript, then the server-side validation works perfectly fine.
 
I hope you find this article helpful, in next article we will learn Validation in ASP.NET MVC application.


Similar Articles