Question : Form Validation

If i had a basic form for example with the feilds firstname, secondname and age like the the attached example. How can i construct a basic validator with javascript that will make sure that only a number has been inputed into the age feild?

Thanks
1:
2:
3:
4:
5:
6:
<form name="input" action="html_form_action.asp" method="get">
First Name: <input type="text" name="fname" />
Second Name: <input type="text" name="sname" />
Age: <input type="text" name="age" />
<input type="submit" value="Submit" />
</form>

Answer : Form Validation

Just copy and paste the code below and you should be good for validating textbox for integers on client side. copy the first part on web page and 2nd part on code behind and you should be good to go.

<head runat="server">
    <title>Untitled Page</title>
 <script language="javascript" type="text/javascript">
function validate()
{  
  if (document.getElementById("<%=NameTextBox.ClientID%>").value=="")
     {
               alert("Zip Code is not valid");
               document.getElementById("<%=NameTextBox.ClientID%>").focus();
               return false;
     }
     var digits="0123456789";
     var temp;
     for (var i=0;i<document.getElementById("<%=NameTextBox.ClientID %>").value.length;i++)
     {
               temp=document.getElementById("<%=NameTextBox.ClientID%>").value.substring(i,i+1);
               if (digits.indexOf(temp)==-1)
               {
                        alert("Please enter only numbers");
                        document.getElementById("<%=NameTextBox.ClientID%>").focus();
                        return false;
               }
     }
     return true;
}
</script>  
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:TextBox ID="NameTextBox" runat="server"></asp:TextBox>
    <asp:Button ID="SubmitButton" runat="server" Text="Submit"
            onclick="SubmitButtong_Click" />
    <asp:Label ID="label1" runat="server"></asp:Label>

    </div>
    </form>
</body>
onclient side just paste this code and you should be good to go.

 protected void Page_Load(object sender, EventArgs e)
        {
            SubmitButton.Attributes.Add("onclick", "return validate()");
        }

Good Luck.
Random Solutions  
 
programming4us programming4us