PHP Form Validation
The HTML form we will be working at in these chapters, contains various input fields: required and optional text fields, radio buttons, and a submit button:
• PHP Form Validation
Example
The validation rules for the form above are as follows:
Field | Validation Rules |
---|---|
Name | Required. + Must only contain letters and whitespace |
Required. + Must contain a valid email address (with @ and .) | |
Website | Optional. If present, it must contain a valid URL |
Comment | Optional. Multi-line input field (textarea) |
Gender | Required. Must select one |
• Text Fields
The name, email, and website fields are text input elements, and the comment field is a textarea. The HTML code looks like this:
Name: <input type="text" name="name"> E-mail: <input type="text" name="email"> Website: <input type="text" name="website"> Comment: <textarea name="comment" rows="5" cols="40"></textarea>
• Radio Buttons
The gender fields are radio buttons and the HTML code looks like this:
Gender: <input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="other">Other
• The Form Element
The HTML code of the form looks like this:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
When the form is submitted, the form data is sent with method="post".