Lets have a look how to validate a HTML form using Javascript
HTML code:
<form action="#" method="post"; onsubmit="return form();" name="myform">
<table>
<tr>
<td>username</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td>password</td>
<td><input type="password" name="pword" /></td>
</tr>
<tr>
<td>email</td>
<td><input type="text" name="email"/></td>
</tr>
<tr>
<td>gender</td>
<td><select name="gen">
<option>male</option>
<option>female</option>
</select></td>
</tr>
<tr>
<td></td>
<td align="left"><input type="submit" name="submit" value="register" /></td>
</tr>
</table>
</form>
</div>
Javascript code for Validation:
<script type="text/javascript">
function form()
{
var name=document.myform.name;
var pwd= document.myform.pword;
var email=document.myform.email;
if(name.value=="")
{
window.alert("enter your name");
name.focus();
return false;
}
if(pwd.value=="")
{
window.alert("enter your password");
pwd.focus();
return false;
}
if(email.value=="")
{
window.alert("enter your email");
email.focus();
return false;
}
}
</script>
HTML code:
<form action="#" method="post"; onsubmit="return form();" name="myform">
<table>
<tr>
<td>username</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td>password</td>
<td><input type="password" name="pword" /></td>
</tr>
<tr>
<td>email</td>
<td><input type="text" name="email"/></td>
</tr>
<tr>
<td>gender</td>
<td><select name="gen">
<option>male</option>
<option>female</option>
</select></td>
</tr>
<tr>
<td></td>
<td align="left"><input type="submit" name="submit" value="register" /></td>
</tr>
</table>
</form>
</div>
Javascript code for Validation:
<script type="text/javascript">
function form()
{
var name=document.myform.name;
var pwd= document.myform.pword;
var email=document.myform.email;
if(name.value=="")
{
window.alert("enter your name");
name.focus();
return false;
}
if(pwd.value=="")
{
window.alert("enter your password");
pwd.focus();
return false;
}
if(email.value=="")
{
window.alert("enter your email");
email.focus();
return false;
}
}
</script>
No comments:
Post a Comment