One of the most efficient methods to validate or verify the user input in web forms is by using client side JavaScript. Suppose you have a web form containing three text fields - Name, Email and Phone Number and two buttons – Submit and Reset. The user fills up all the required fields, and now it is your turn to verify the form input. However, in cases when there are too many fields in the form, this JavaScript verification becomes complex.
See the following JavaScript source code for verifying the above form.
<head>
<title>Javascript Verification Page</title>
<script language="JavaScript">
Hiding script contents from old browsers
function VerifyData() {
Checking Form Data
Following is the source code to check form data. Firstly you have to create a variable for keeping a track of whether the form is valid. Then initialize the variable value to 1, which indicates that the form is valid until this value changes in the due course.
var valid = 1
if (document.Customer.FirstLast.value == "") {
valid = 0
}
if (document.Customer.Email.value == "") {
valid = 0
}
if (!CheckPhoneNumber(document.Customer.Phone.value)) {
valid = 0
}
Submitting the Form
Next comes the decision, whether to submit the form or not.
if (!valid) {
alert("Complete all the fields and enter a valid phone number")
}
return valid
}
function CheckPhoneNumber(TheNumber) {
var valid = 1
var GoodChars = "0123456789()-+ "
var i = 0
if (TheNumber=="") {
// Return false if number is empty
valid = 0
}
for (i =0; i <= TheNumber.length -1; i++) {
if (GoodChars.indexOf(TheNumber.charAt(i)) == -1) {
// Note: Remove the comments from the following line to see this
// for loop in action.
// alert(TheNumber.charAt(i) + " is no good.")
valid = 0
} // End if statement
} // End for loop
return valid
}
// end hiding contents from old browsers -->
</script>
<link rel="SHORTCUT ICON" href="http://brighthub.com/favicon.ico">
</head>
<body>
<h2>Sample page for JavaScript Form Verification</h2>
Press the submit button to verify form data.
<p>
<form name="Customer" action=""
method="POST" onsubmit="return VerifyData()">
Your name:
<input type="text" name="FirstLast" size="30" maxlength="75" value=""> <br>
Your email:
<input type="text" name="Email" size="30" maxlength="75" value=""> <br>
Your phone number:
<input type="text" name="Phone" size="30" maxlength="75" value=""> <br>
<input type="submit">
<input type="reset">
</form>
<p>
</body>
</html>