PHP:Form Series, Part 1: Validators & Client-side Validation
(Page 2 out of 3)Before we look at the validators, let's first look at the basic PHP:Form syntax. It has a really simple syntax, because it's basic HTML. To create a new form, use the
tags, like so:
... form html goes here ...
That's all that is really necessary. But you must also tell the form to display, using PHP, like so:
Those two things are the only things absolutely necessary to create and display a new form. Of course, nothing will be displayed yet because you haven't created any input fields. To see a simple form in action, have a look at demo 1
Let's move on to validators now. Validators are used to validate form fields, and just like the form tags, they are simple html, for example:
You can either place validators in between the form tags, or outside the form tags. If you place them outside the form tags you must specify the form name (using the 'form' attribute).
A simple form with a validator would look like this:
// Include PHP:Form
include ('../phpform.php');
// Begin form:
?>
"font-weight:bold;color:red;">Please enter your name
Name: "text" name="name" />
"submit" value="Go!" />
if ($_FORMS->validate ('example') == true) {
// Show POST'ed values
echo ''
;
print_r ($_POST);
echo '';
} else {
// Display form
$_FORMS->display ("example");
}
?>
As you can see in the code we created a validator that has the required attribute set to "true". That means that this validator just checks whether the value of the input field isn't empty.
There are 5 different kinds of validators:
- Required: they are used to make sure an input field isn't empty, like I just demonstrated.
- Numeric: they are used to make sure an input field only contains numbers, and nothing else.
- Regex: they can be used to specifiy a regular expression that an input field must match.
- Callback: callback validators can take a callback function that is run on the server-side. That callback function is passed the value of the input field, and the function must return true or false. This is used for really advanced validation (and it's likely you will hardly ever use the callback validator)
- Name: name validator can be used to display a message or error only when you want to. They can only be shown when you manually show them using the trigger_error ('form', 'errorname') method.
Then in PHP:
$_FORMS->trigger_error ('example', 'mymsg');
?>
When using validators, you will probably want to check if a form validates or not. To do this, use the validate() method, as seen in demo 2:
echo 'It validates!';
} else {
echo It 'doesn\'t validate!';
}