Client Side Validation For Email In ASP.NET

This article explains how to do client-side validation for an email in ASP.NET.

Introduction

Validation is a primary requirement for any application. Validations play a very important role for an application. Using validation we can ensure that the data is at a different level. Using the validation we can check that the data input by the user is proper or that there is an error in the data. Using validation we check the data before it goes to the server. If the data is not validated then we send a message for the end user to please input valid data to proceed further. The main purose of validation is to prevent a round-trip to the server before the user is informed about the errors in the form or page. The validation controls are a way to tell the user that the page has errors if relevant. Here every validation control has a valid property that always returns true if there is no error otherwise it always returns false.

There are the following two types of validation:

  • Client-side Validation
  • Server-side Validation

Client-side Validation

When we do the validation using a script like JavaScript on a form then that works in the end-user browser to check the validation on the form, in other words check that the data entered by the user in the form is valid before doing the page post-back event to the server. Then this type of validation is known as client-side validations. Client-side validations work quickly compared to server-side validation. In the Client-Side Validation Control we depend on the browser and the scripting language.

Server-side Validation

When we make a form for ASP.NET and the user inputs the data and requests to send it to the server and then the validation is done to validate the input then that type of validation is called server-side validation. A Server-Side Validation Control is more secure than a Client-Side Validation Control.

Here we discuss the Client-Side Validation Control on a grid view. Here we see how the client-side validation works for a grid view. As we know a grid view is a very powerful control to show data, it provides many features like paging, inserting, deleting, updating the data using the grid view but in this article we learn how to validate the data from a client-side validation in the grid view. So let's see the step-by-step process to make the Client-Side Validation Control for the grid view control.

Step 1

Open Visual Studio, create a project, select C# as the language and select the ASP. NET web application option from the list.


Step 2

Go the the Solution Explorer, right-click on it add a new item, select a web form and add it.



Step 3

Now make a grid view. Our grid view aspx page has some columns. Here we have seven columns in our grid view; they are Name, Father Name, Email, Date of Birth, Class, Address and RollNo.

Now when we create a grid view with the preceding column then every column has a template field with it. In each template field we have the following two fields:

  • Item template field
  • Edit Item template field

The item Template field is used to show the value that we added to the grid view when the grid view is loaded. Here we use a label to show the value. We use the %Bind function to bind the value that we added to the grid view. The Edit item template field works when we click on the edit button in the grid view. Here we generate a TextBox, Dropdown list and radio button depending on our needs of edit mode. We make the auto-generated column false from the grid view and fire the three events in the grid view update, edit and cancel to update a record in the grid view.

Step 4

When we do the preceding procedure then the design part of our grid view is something like this.

Code

  1. <form id="form1" runat="server">  
  2.    <div>  
  3.     <asp:GridView ID="gridcontrol" runat="server" AutoGenerateColumns="false" OnRowEditing="gridcontrol_edit"  
  4.            OnRowUpdating="gridcontrol_update" OnRowCancelingEdit="gridcontrol_cancel" AlternatingRowStyle-BackColor="Chartreuse" AlternatingRowStyle-ForeColor="Black">  
  5.            <Columns>  
  6.                <asp:TemplateField HeaderText="Name">  
  7.                    <ItemTemplate>  
  8.                        <asp:Label ID="lblName" runat="server" Text='<%#Bind("Name") %>'></asp:Label>  
  9.                    </ItemTemplate>  
  10.                    <EditItemTemplate>  
  11.                        <asp:TextBox ID="txtName" runat="server" Text='<%#Bind("Name") %>' />  
  12.                    </EditItemTemplate>  
  13.                </asp:TemplateField>  
  14.                <asp:TemplateField HeaderText="Father Name">  
  15.                    <ItemTemplate>  
  16.                        <asp:Label ID="lblFatherName" runat="server" Text='<%#Bind("FatherName") %>'></asp:Label>  
  17.                    </ItemTemplate>  
  18.                    <EditItemTemplate>  
  19.                        <asp:TextBox ID="txtFatherName" runat="server" Text='<%#Bind("FatherName") %>' />  
  20.                    </EditItemTemplate>  
  21.                </asp:TemplateField>  
  22.                <asp:TemplateField HeaderText="Email">  
  23.                    <ItemTemplate>  
  24.                        <asp:Label ID="lblEmail" runat="server" Text='<%#Bind("Email") %>'></asp:Label>  
  25.                    </ItemTemplate>  
  26.                    <EditItemTemplate>  
  27.                        <asp:TextBox ID="txtEmail" runat="server" Text='<%#Bind("Email") %>' />  
  28.                    </EditItemTemplate>  
  29.                </asp:TemplateField>  
  30.                <asp:TemplateField HeaderText="Date Of Birth">  
  31.                    <ItemTemplate>  
  32.                        <asp:Label ID="lblDOB" runat="server" Text='<%#Bind("DOB") %>'></asp:Label>  
  33.                    </ItemTemplate>  
  34.                    <EditItemTemplate>  
  35.                        <asp:TextBox ID="txtDOB" runat="server" Text='<%#Bind("DOB") %>' />  
  36.                    </EditItemTemplate>  
  37.                </asp:TemplateField>  
  38.                <asp:TemplateField HeaderText="Class">  
  39.                    <ItemTemplate>  
  40.                        <asp:Label ID="lblClass" runat="server" Text='<%#Bind("Class") %>'></asp:Label>  
  41.                    </ItemTemplate>  
  42.                    <EditItemTemplate>  
  43.                        <asp:TextBox ID="txtClass" runat="server" Text='<%#Bind("Class") %>' />  
  44.                    </EditItemTemplate>  
  45.                </asp:TemplateField>  
  46.                <asp:TemplateField HeaderText="Address">  
  47.                    <ItemTemplate>  
  48.                        <asp:Label ID="lblAddress" runat="server" Text='<%#Bind("Address") %>'></asp:Label>  
  49.                    </ItemTemplate>  
  50.                    <EditItemTemplate>  
  51.                        <asp:TextBox ID="txtAddress" runat="server" Text='<%#Bind("Address") %>' />  
  52.                    </EditItemTemplate>  
  53.                </asp:TemplateField>  
  54.                <asp:TemplateField HeaderText="RollNo">  
  55.                    <ItemTemplate>  
  56.                        <asp:Label ID="lblRollNo" runat="server" Text='<%#Bind("RollNo") %>'></asp:Label>  
  57.                    </ItemTemplate>  
  58.                    <EditItemTemplate>  
  59.                        <asp:TextBox ID="txtRollNo" runat="server" Text='<%#Bind("RollNo") %>' />  
  60.                    </EditItemTemplate>  
  61.                </asp:TemplateField>  
  62.                <asp:CommandField ShowEditButton="true" HeaderText="Edit" />  
  63.            </Columns>  
  64.        </asp:GridView>  
  65.    </div>  
  66.    </form>  


Step 5

Here we use a Data table (as a container to store the data) and the view state (View state is a state management technique that is used to preserve the data during the Page Post-back event ). So here we did not use the database. Here we added the data from the Data Tables with the view state property and to edit and update the data. So the code for that is given below.

Code
  1. DataTable dtg1  
  2.        {  
  3.            get  
  4.            {  
  5.                return (DataTable)ViewState["dtg1"];  
  6.            }  
  7.            set  
  8.            {  
  9.                ViewState["dtg1"] = value;  
  10.            }  
  11.        }  
  12.        protected void Page_Load(object sender, EventArgs e)  
  13.        {  
  14.            if (!IsPostBack)  
  15.            {  
  16.              
  17.                DataTable dt = new DataTable();  
  18.                dt.Columns.Add(new DataColumn("Name"));  
  19.                dt.Columns.Add(new DataColumn("FatherName"));  
  20.                dt.Columns.Add(new DataColumn("Email"));  
  21.                dt.Columns.Add(new DataColumn("DOB"));  
  22.                dt.Columns.Add(new DataColumn("Class"));  
  23.                dt.Columns.Add(new DataColumn("Address"));  
  24.                dt.Columns.Add(new DataColumn("RollNo"));  
  25.   
  26.                
  27.                DataRow dr = dt.NewRow();  
  28.                dr["Name"] = "Vaivbhav Koushik";  
  29.                dr["FatherName"] = "shri Ramshankar";   
  30.                dr["Email"] = "VK123@gmail.com";  
  31.                dr["DOB"] = "06/22/1987";  
  32.                dr["Class"] = "MCA";  
  33.                dr["Address"] = "Noida";  
  34.                dr["RollNo"] = 121;  
  35.   
  36.                dt.Rows.Add(dr);  
  37.   
  38.                dr = dt.NewRow();  
  39.                dr["Name"] = "Ravi Kumar";  
  40.                dr["FatherName"] = "Anuj Pandey";  
  41.                dr["Email"] = "Kumarravi@gmail.com";  
  42.                dr["DOB"] = "02/12/1970";  
  43.                dr["Class"] = "MBA";  
  44.                dr["Address"] = "Noida";  
  45.                dr["RollNo"] = 122;  
  46.   
  47.                dt.Rows.Add(dr);  
  48.   
  49.                dr = dt.NewRow();  
  50.                dr["Name"] = "Sanjay Gupta";  
  51.                dr["FatherName"] = "Ashok Gupta";  
  52.                dr["Email"] = "Gupta121@gmail.com";  
  53.                dr["DOB"] = "01/10/1990";  
  54.                dr["Class"] = "Btech";  
  55.                dr["Address"] = "Delhi";  
  56.                dr["RollNo"] = 123;  
  57.   
  58.                dt.Rows.Add(dr);  
  59.                dr = dt.NewRow();  
  60.                dr["Name"] = "Shambhu Bharadwaj";  
  61.                dr["FatherName"] = "shubham bharadwaj";  
  62.                dr["Email"] = "121shambhu@gmail.com";  
  63.                dr["DOB"] = "03/28/1990";  
  64.                dr["Class"] = "MCA";  
  65.                dr["Address"] = "Noida";  
  66.                dr["RollNo"] = 124;  
  67.   
  68.                dt.Rows.Add(dr);  
  69.                dtg1 = dt;  
  70.                gridviewbind();  
  71.            }  
  72.        }  
Step 6

Then we make a function to bind the data from the grid view and call this function in the page load event by which all the records that we added to the data tables shows in the grid view when our page is loaded on the server.

Code
  1. private void gridviewbind()  
  2.        {  
  3.            gridcontrol.DataSource = ViewState["dtg1"];  
  4.            gridcontrol.DataBind();  
  5.        }  
Step 7

So here our grid view looks like this. Here we add four records to the data table so there will be four records in the grid view. You can add more or less records depending on your needs.



Step 8

Here in the grid view at the last column you see an edit link. When you click on it the edit link is hidden and you will see the update and cancel link, these links are nothing new. These are the event that we do in our grid view to edit, update and cancel the record updating. So the coding of these three events is below.

Code Edit Event
  1. protected void gridcontrol_edit(object sender, GridViewEditEventArgs e)  
  2.        {  
  3.            gridcontrol.EditIndex = e.NewEditIndex;  
  4.            gridviewbind();  
  5.        }  
Code Cancel Event
  1. protected void gridcontrol_cancel(Object sender, GridViewCancelEditEventArgs e)  
  2.         {  
  3.   
  4.             gridcontrol.EditIndex = -1;  
  5.             gridviewbind();  
  6.         }  
Code Update Event
  1. protected void gridcontrol_update(object sender, GridViewUpdateEventArgs e)  
  2.         {  
  3.   
  4.             DataTable dtg1 = (DataTable)ViewState["dtg1"];  
  5.             GridViewRow gr = gridcontrol.Rows[e.RowIndex];  
  6.             dtg1.Rows[gr.DataItemIndex]["Name"] = ((TextBox)(gr.Cells[0].FindControl("txtName"))).Text;  
  7.             dtg1.Rows[gr.DataItemIndex]["FatherName"] = ((TextBox)(gr.Cells[1].FindControl("FatherName"))).Text;  
  8.             dtg1.Rows[gr.DataItemIndex]["Email"] = ((TextBox)(gr.Cells[2].FindControl("txtEmail"))).Text;  
  9.             dtg1.Rows[gr.DataItemIndex]["DOB"] = ((TextBox)(gr.Cells[3].FindControl("txtDOB"))).Text;  
  10.             dtg1.Rows[gr.DataItemIndex]["Class"] = ((TextBox)(gr.Cells[4].FindControl("txtClass"))).Text;  
  11.             dtg1.Rows[gr.DataItemIndex]["Address"] = ((TextBox)(gr.Cells[4].FindControl("txtAddress"))).Text;  
  12.             dtg1.Rows[gr.DataItemIndex]["RollNo"] = ((TextBox)(gr.Cells[5].FindControl("RollNo"))).Text;  
  13.             gridcontrol.EditIndex = -1;  
  14.             gridviewbind();  
  15.         }  
Step 9

When we click on the edit link then the controls (Texbox, Checkbox and Radio button) are created as you specified in the Edit item template field. So here when we click on it then there are TextBoxes generated like in the following picture.



Step 10

Now we make the validation for the Email, in other words if the end user wants to update the Email id then at the client side it will be determined whether or not the input email id is valid. If the email id is not valid then an alert is shown "please enter a valid email id". So first we determine the Email TextBox location in our grid view control. So first we have the function like this.

Code
  1. function validateEmail(email) {  
  2.             var email = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;  
  3.             return email.test(email);  
  4.         }  
This function checks the format of the Email, if the input Email format does not match this format then it shows the error that you have entered a wrong email id.

Step 11

Now we create the Client-Side Validation Control for the Email field using JavaScript.

Code
  1. $("#gridcontrol tr input[id*='txtEmail']").each(function () {  
  2.                $(this).change(function (event) {  
  3.                    if (!validateEmail($(this).val())) {  
  4.                        alert("Please enter a valid email id");  
  5.                        $(this).addClass('errorClass');  
  6.                        event.preventDefault();  
  7.   
  8.                        isValidated = false;  
  9.                    }  
  10.                    else {  
  11.                        $(this).removeClass('errorClass');  
  12.                        isValidated = true;  
  13.                    }  
  14.                });  
  15.            });  
Using the this code first we find all TextBoxes in our grid view control. Here the first line of the code does this. Here we determine that the control that has an id Email. Here we use the change event that is written in the second line in the given code. Now when we run our application and edit the email and if we provide an incorrectly formatted Email then it shows an alert box saying "please provide a valid email id" and the color of that text box will be Blue.



After clicking on the Alert Box you will see a grid view like this.



Summary

So here we learned what a Client-Side Validation Control is, how they work and what the benefits are of a Client-Side Validation Control. In this article we used a data table and a view state to add the data to the grid view. You can use a database to add the data to the grid view and then from JavaScript you make the validation depending on your needs. Here I told you about the email validation control and how it works. I hope this article will be useful for the users.