Forms are most commonly used HTML elemnts. Sometimes we need some fields of these forms to be mandatory. This can be done in php as well but the form will need to be submitted and the user will have to fill all the field again with the correct values, which is quite irritating. We can enhance the user experience by doing form validation using Javascript. For this purpose i wrote a very simple and easy to understand code. This is a sample code you can use it according to your need.
<!--Put this code in the head section of the page-->
<script type="text/javascript" language="javascript">
function validate_form()
{
//For empty field validation
if (document.getElementById('name').value=="")
{
alert ('Please enter a valid name.');
document.getElementById('name').focus();
return false;
}
//For Email address validation
var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
if (!filter.test(document.getElementById('email').value))
{
alert("Please input a valid email address!")
document.getElementById('email').focus();
return false;
}
//For empty field validation
if (document.getElementById('phone').value=="")
{
alert ('Please enter a valid phone number.');
document.getElementById('phone').focus();
return false;
}
//For numeric field validation
if (isNaN(document.getElementById('phone').value))
{
alert ('Please enter only numeric values.');
document.getElementById('phone').focus();
return false;
}
}
</script>
<!--End of validation code-->
HTML Form
<form id="form1" name="form1" method="post" action="" onsubmit="return validate_form()">
<table width="400" border="0" align="center" cellpadding="4" cellspacing="0">
<tr>
<td colspan="2"><strong>Validate Form:</strong></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td>Name:</td>
<td><label>
<input type="text" name="name" id="name" />
</label></td>
</tr>
<tr>
<td>Email:</td>
<td><label>
<input type="text" name="email" id="email" />
</label></td>
</tr>
<tr>
<td>Phone Number:</td>
<td><label>
<input type="text" name="phone" id="phone" />
</label></td>
</tr>
<tr>
<td colspan="2" align="center"><label>
<input type="submit" name="button" id="button" value="Submit" />
</label></td>
</tr>
</table>
</form>
So that was some basic html form validation using javascript. If you guyz have any questions, please feel free to ask by commenting on this post.
No comments:
Post a Comment