Wednesday, 26 December 2012

JavaScript Form Validation | PHP Tutorial For Beginners


WHY CLIENT SIDE FORM VALIDATION???

Forms validation on the client-side is essential — it saves time and bandwidth, and gives you more options to point out to the user where they've gone wrong in filling out the form. But apart from this you should also use server side validation. because people visit your site may use an old browser or have JavaScript disabled, which will break client-only validation. Client and server-side validation complement each other, and as such, they really shouldn't be used independently.

WHY IS CLIENT SIDE FORM VALIDATION IS GOOD?

It’s a fast form of validation: If something’s wrong, the event is triggered upon submission of the form or on change of focus.
You can safely display only one error at a time and focus on the wrong field, to help ensure that the user correctly fills in all the details you need.

The two key approaches to client-side form validation are:
1- Display the errors one by one, focusing on the offending field.
2- Display all errors simultaneously, server-side validation style.

While displaying all errors simultaneously is required for server-side validation, the better method for validation on the client-side is to show one error at a time. This makes it possible to highlight only the field that has been incorrectly completed, which in turn makes revising and successfully submitting the form much easier for the visitor. If you present users with all errors at the same time, most people will try to remember and correct them at once, instead of attempting to re-submit after each correction.

Here is the HTML code for the form validation:-


<html>
<head>
<title>Java script form validation</title>

<script type="text/javascript">

function form_validate()
{

if( document.Form.Name.value == "" )
{
alert( "Please enter your first name." );
document.Form.Name.focus() ;
return false;
}
if( document.Form.EMail.value == "" )
{
alert( "Please enter your E-mail address." );
document.Form.EMail.focus() ;
return false;
}
if( document.Form.Zip.value == "" ||
isNaN( document.Form.Zip.value ) ||
document.Form.Zip.value.length != 5 )
{
alert( "Please enter a zip in the format *****." );
document.Form.Zip.focus() ;
return false;
}
}

</script>

</head>
<body>

<form name="Form" onsubmit="return(form_validate());">
<table>
<tr>
<td>First Name:</td>
<td><input type="text" name="Name" /></td>
</tr>
<tr>
<td>E-Mail Address:</td>
<td><input type="text" name="EMail" /></td>
</tr>
<tr>
<td>Postal Code:</td>
<td><input type="text" name="Zip" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>

</body>
</html>

No comments:

Post a Comment