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
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:
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
- <form id="form1" runat="server">
- <div>
- <asp:GridView ID="gridcontrol" runat="server" AutoGenerateColumns="false" OnRowEditing="gridcontrol_edit"
- OnRowUpdating="gridcontrol_update" OnRowCancelingEdit="gridcontrol_cancel" AlternatingRowStyle-BackColor="Chartreuse" AlternatingRowStyle-ForeColor="Black">
- <Columns>
- <asp:TemplateField HeaderText="Name">
- <ItemTemplate>
- <asp:Label ID="lblName" runat="server" Text='<%#Bind("Name") %>'></asp:Label>
- </ItemTemplate>
- <EditItemTemplate>
- <asp:TextBox ID="txtName" runat="server" Text='<%#Bind("Name") %>' />
- </EditItemTemplate>
- </asp:TemplateField>
- <asp:TemplateField HeaderText="Father Name">
- <ItemTemplate>
- <asp:Label ID="lblFatherName" runat="server" Text='<%#Bind("FatherName") %>'></asp:Label>
- </ItemTemplate>
- <EditItemTemplate>
- <asp:TextBox ID="txtFatherName" runat="server" Text='<%#Bind("FatherName") %>' />
- </EditItemTemplate>
- </asp:TemplateField>
- <asp:TemplateField HeaderText="Email">
- <ItemTemplate>
- <asp:Label ID="lblEmail" runat="server" Text='<%#Bind("Email") %>'></asp:Label>
- </ItemTemplate>
- <EditItemTemplate>
- <asp:TextBox ID="txtEmail" runat="server" Text='<%#Bind("Email") %>' />
- </EditItemTemplate>
- </asp:TemplateField>
- <asp:TemplateField HeaderText="Date Of Birth">
- <ItemTemplate>
- <asp:Label ID="lblDOB" runat="server" Text='<%#Bind("DOB") %>'></asp:Label>
- </ItemTemplate>
- <EditItemTemplate>
- <asp:TextBox ID="txtDOB" runat="server" Text='<%#Bind("DOB") %>' />
- </EditItemTemplate>
- </asp:TemplateField>
- <asp:TemplateField HeaderText="Class">
- <ItemTemplate>
- <asp:Label ID="lblClass" runat="server" Text='<%#Bind("Class") %>'></asp:Label>
- </ItemTemplate>
- <EditItemTemplate>
- <asp:TextBox ID="txtClass" runat="server" Text='<%#Bind("Class") %>' />
- </EditItemTemplate>
- </asp:TemplateField>
- <asp:TemplateField HeaderText="Address">
- <ItemTemplate>
- <asp:Label ID="lblAddress" runat="server" Text='<%#Bind("Address") %>'></asp:Label>
- </ItemTemplate>
- <EditItemTemplate>
- <asp:TextBox ID="txtAddress" runat="server" Text='<%#Bind("Address") %>' />
- </EditItemTemplate>
- </asp:TemplateField>
- <asp:TemplateField HeaderText="RollNo">
- <ItemTemplate>
- <asp:Label ID="lblRollNo" runat="server" Text='<%#Bind("RollNo") %>'></asp:Label>
- </ItemTemplate>
- <EditItemTemplate>
- <asp:TextBox ID="txtRollNo" runat="server" Text='<%#Bind("RollNo") %>' />
- </EditItemTemplate>
- </asp:TemplateField>
- <asp:CommandField ShowEditButton="true" HeaderText="Edit" />
- </Columns>
- </asp:GridView>
- </div>
- </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
- DataTable dtg1
- {
- get
- {
- return (DataTable)ViewState["dtg1"];
- }
- set
- {
- ViewState["dtg1"] = value;
- }
- }
- protected void Page_Load(object sender, EventArgs e)
- {
- if (!IsPostBack)
- {
-
- DataTable dt = new DataTable();
- dt.Columns.Add(new DataColumn("Name"));
- dt.Columns.Add(new DataColumn("FatherName"));
- dt.Columns.Add(new DataColumn("Email"));
- dt.Columns.Add(new DataColumn("DOB"));
- dt.Columns.Add(new DataColumn("Class"));
- dt.Columns.Add(new DataColumn("Address"));
- dt.Columns.Add(new DataColumn("RollNo"));
-
-
- DataRow dr = dt.NewRow();
- dr["Name"] = "Vaivbhav Koushik";
- dr["FatherName"] = "shri Ramshankar";
- dr["Email"] = "[email protected]";
- dr["DOB"] = "06/22/1987";
- dr["Class"] = "MCA";
- dr["Address"] = "Noida";
- dr["RollNo"] = 121;
-
- dt.Rows.Add(dr);
-
- dr = dt.NewRow();
- dr["Name"] = "Ravi Kumar";
- dr["FatherName"] = "Anuj Pandey";
- dr["Email"] = "[email protected]";
- dr["DOB"] = "02/12/1970";
- dr["Class"] = "MBA";
- dr["Address"] = "Noida";
- dr["RollNo"] = 122;
-
- dt.Rows.Add(dr);
-
- dr = dt.NewRow();
- dr["Name"] = "Sanjay Gupta";
- dr["FatherName"] = "Ashok Gupta";
- dr["Email"] = "[email protected]";
- dr["DOB"] = "01/10/1990";
- dr["Class"] = "Btech";
- dr["Address"] = "Delhi";
- dr["RollNo"] = 123;
-
- dt.Rows.Add(dr);
- dr = dt.NewRow();
- dr["Name"] = "Shambhu Bharadwaj";
- dr["FatherName"] = "shubham bharadwaj";
- dr["Email"] = "[email protected]";
- dr["DOB"] = "03/28/1990";
- dr["Class"] = "MCA";
- dr["Address"] = "Noida";
- dr["RollNo"] = 124;
-
- dt.Rows.Add(dr);
- dtg1 = dt;
- gridviewbind();
- }
- }
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
- private void gridviewbind()
- {
- gridcontrol.DataSource = ViewState["dtg1"];
- gridcontrol.DataBind();
- }
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
- protected void gridcontrol_edit(object sender, GridViewEditEventArgs e)
- {
- gridcontrol.EditIndex = e.NewEditIndex;
- gridviewbind();
- }
Code Cancel Event
- protected void gridcontrol_cancel(Object sender, GridViewCancelEditEventArgs e)
- {
-
- gridcontrol.EditIndex = -1;
- gridviewbind();
- }
Code Update Event
- protected void gridcontrol_update(object sender, GridViewUpdateEventArgs e)
- {
-
- DataTable dtg1 = (DataTable)ViewState["dtg1"];
- GridViewRow gr = gridcontrol.Rows[e.RowIndex];
- dtg1.Rows[gr.DataItemIndex]["Name"] = ((TextBox)(gr.Cells[0].FindControl("txtName"))).Text;
- dtg1.Rows[gr.DataItemIndex]["FatherName"] = ((TextBox)(gr.Cells[1].FindControl("FatherName"))).Text;
- dtg1.Rows[gr.DataItemIndex]["Email"] = ((TextBox)(gr.Cells[2].FindControl("txtEmail"))).Text;
- dtg1.Rows[gr.DataItemIndex]["DOB"] = ((TextBox)(gr.Cells[3].FindControl("txtDOB"))).Text;
- dtg1.Rows[gr.DataItemIndex]["Class"] = ((TextBox)(gr.Cells[4].FindControl("txtClass"))).Text;
- dtg1.Rows[gr.DataItemIndex]["Address"] = ((TextBox)(gr.Cells[4].FindControl("txtAddress"))).Text;
- dtg1.Rows[gr.DataItemIndex]["RollNo"] = ((TextBox)(gr.Cells[5].FindControl("RollNo"))).Text;
- gridcontrol.EditIndex = -1;
- gridviewbind();
- }
Step 9When 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
- function validateEmail(email) {
- 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,}))$/;
- return email.test(email);
- }
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
- $("#gridcontrol tr input[id*='txtEmail']").each(function () {
- $(this).change(function (event) {
- if (!validateEmail($(this).val())) {
- alert("Please enter a valid email id");
- $(this).addClass('errorClass');
- event.preventDefault();
-
- isValidated = false;
- }
- else {
- $(this).removeClass('errorClass');
- isValidated = true;
- }
- });
- });
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.