Form Validation
Validating a form
You can perform form validation before a form is submitted via JavaScript or after the form is submitted via PHP.
I've actually already demonstrated simple validation using PHP in Form Processing with PHP: Part 1, with the input.php script. After the form is submitted, the script checks to see whether a variable does or does not exist.
PHP Code:
<?php //check if submit button clicked and the input field isn't empty, print hello if ($submit == "click" && $UserName !=""): echo "Hello, $UserName"; //if submit button clicked and the input field is empty, print error elseif ($UserName =="" && $submit == "click"): echo "You did not enter a name."; else: echo " <html><body> <form method="post" action="input.php"> Enter Your Name <input type="text" name="UserName"><br/> <input type="submit" name="submit" value="click"> </form> </body></html> "; endif; ?>
See it in action. ¦ Get complete code.
You can also use regular expressions with the ereg() and eregi() functions to validate the values submitted by a form. Regular expressions examine a string and search for patterns and variations to determine whether they match the search criteria you set.
An example:
This regular expression tests true if the user has entered only characters, from a to z, in lowercase or uppercase, and numbers from zero to nine. Also, checks whether the string is four to twelve characters in length.
The ^ indicates the beginning of a string and the $ the end of the string.
if (!ereg("^[A-Za-z0-9]{4,12}$",$Username)): echo "Your username must be at least 4 character, but not more than 12 characters.";
PHPBuilder.com has a good tutorial demonstrating how to use regular expressions called Learning to Use Regular Expressions by Example.
You could also use JavaScript to do client-side validation of form values before the form is submitted to a PHP script. Irt.org has a great tutorial - Addressing Form Field Validation with Regular Expressions and JavaScript 1.2 that explains how to use JavaScript and regular expressions to do form validation.
Here is an example:
JavaScript Code:
<script LANGUAGE="JavaScript" type="text/javascript"> <!-- . . . for (var i = 0; i < string.length; i++) { if (iChars.indexOf(string.charAt(i)) != -1) // if one of the characters is found then the string is invalid return false; } // otherwise the string is valid return true; } function isReady(form) { if (isProper(form.firstname.value) == false) { alert("Please enter your firstname"); form.firstname.focus(); return false; } return true; } //--> </SCRIPT>