Tuesday, August 31, 2010

Validating form input using JavaScript

Forms are widely used on the Internet. The form input is often being sent back to the server. But how can you be certain that a valid input was done by the user? With the help of JavaScript the form input can easily be checked before sending it over the Internet.

Here it goes Firstle lets not give chance to enter empty fields.

Validation for Blank fields

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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 runat="server">
<title>Untitled Page</title>

<script type="text/javascript">
function Verify(){
if(document.getElementById('uidTextBox').value.length==0)
alert("UserId can't be blank");
else if(document.getElementById('pwdTextBox').value.length==0)
alert("Password can't be blank");
else
{
alert("successfully logged in");
window.open("http://www.cooltuts.com/");
}
}
</script>

</head>
<body>
<form id="form1" runat="server">
<div>
<p><asp:TextBox ID="uidTextBox" runat="server" /></p>
<p><asp:TextBox ID="pwdTextBox" runat="server" /></p>
<p><asp:Button ID="btnSubmit" OnClientClick="Verify()" runat="server" Text="Button" /></p>
</div>
</form>
</body>
</html>


Email validation

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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 runat="server">
<title>Untitled Page</title>

<script type="text/javascript">
function Verify(){
if(document.getElementById('emailTextBox').value.length==0)
alert("Email can't be blank");
else if((/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(document.getElementById('emailTextBox').value))==false)
alert("Email Not in Correct Format");
else
{
alert("successfully logged in");
window.open("http://www.cooltuts.com/");
}
}
</script>

</head>
<body>
<form id="form1" runat="server">
<div>
<p><asp:TextBox ID="emailTextBox" runat="server" /></p>
<p><asp:Button ID="btnSubmit" OnClientClick="Verify()" runat="server" Text="Button" /></p>
</div>
</form>
</body>
</html>

No comments:

Post a Comment