Tuesday, February 15, 2011

How to validate all textboxes of the web form on button click event using JavaScript

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default2.aspx.vb" Inherits="Default2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"><head id="Validation" runat="server">   

<title>Validation</title></head><body>    <!-- title of the page!-->

<form id="form1" runat="server">    <div>

<asp:Label ID="lblMessage" runat="server" Text="Enter the Input:"></asp:Label>

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>   
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>

 </div>   

 <asp:Button ID="Button1" runat="server" Text="Validate" OnClientClick="javascript:validateAllTextBoxes();"/> 
            </form></body></html>



<script type="text/javascript">

    //The following function validates all the textboxes exists in the form
    function validateAllTextBoxes() { 
    //The following valiable lists all the input controls 
        var inputControls = document.getElementsByTagName("input");

        for (i = 0; i < inputControls.length; i++) {

        // The following checkes whether its a textbox or not and its empty or  not

        if (inputControls[i].type == "text" && inputControls[i].value == "") {
            alert("Enter Value in " + inputControls[i].name);
            break;
        } 
       } 
    
     } 
</script>

No comments:

Post a Comment