Client-Side Form Verification with JavaScript [Sample] Sample page for JavaScript Tutorial Press the submit button to verify form data. Here's the source code to the above example: <head> <title>Javascript Sample Page</title> <script language="JavaScript"> <!-- to hide script contents from old browsers function VerifyData() { // Source code to check form data goes here. // Create a variable to keep track of whether the form is valid. // Initializing this value to 1 means, in effect, that // the form is valid unless the value changes sometime in the // routine. 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 } // Here we decide whether to submit the form. if (!valid) { alert("Please complete all the form 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://webdeveloper.com/favicon.ico"> </head> <body> <h2>Sample page for JavaScript Tutorial</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> |