Common Predefined Validation Rules (Continued)
Rule Description Usage
CHAPTER 13 ?– FORMS 361
The following example demonstrates the use of the required rule, enforcing clientside
validation by displaying an error message using a JavaScript alert window (HTML_
QuickForm??™s default behavior), or displaying a welcome message should the rule pass
muster:
require_once "HTML/QuickForm.php";
// Instantiate the HTML_QuickForm class
$form = new HTML_QuickForm("login");
// Add text input element for entering username
$form->addElement('text', 'username', 'Your name: ',
array('size' => 20, 'maxlength' => 40));
// Add text input element for entering e-mail address
$form->addElement('text', 'email', 'E-mail address: ',
array('size' => 20, 'maxlength' => 50));
// Add a rule requiring the username
$form->addRule('username', 'Please provide your username.',
'required', null, 'client');
// Add submit button
$form->addElement('submit', null, 'Submit!');
if ($form->validate()) {
echo "Welcome to the restricted site, ".
htmlspecialchars($form->exportValue('username')). ".";
}
// Display the form
$form->display();
?>
362 CHAPTER 13 ?– FORMS
?– Caution HTML_QuickForm harbors an odd side effect: for example, validate() will process
correctly in instances where the minlength or maxlength rule is added but the user neglects to enter
any data into the field. In order to ensure that these rules process correctly, you must also add a
required rule.
Pages:
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438