December 22, 2014
Hot Topics:

Creating Complex, Secure Web Forms with PHP and HTML_QuickForm2

  • May 10, 2010
  • By Jason Gilmore
  • Send Email »
  • More Articles »

Validating the Form

The previous two examples demonstrated how easy it is to create and render forms using HTML_QuickForm2, but they did nothing to inspect and validate user input -- not to mention informing users when the form wasn't successfully completed. You can configure control-specific validation requirements using the addRule() method, as shown here:

$name = $form->addText('name')->setLabel('Your Name:');
$name->addRule('required', 'Please provide your name.');


After having added similar requirements to the other form controls, HTML_QuickForm2 will automatically adjust the rendered form to inform the user of the required fields, as depicted in Figure 3.


Creating Forms with HTML_QuickForm2
Figure 3. Adding Field Requirements

The required rule is just one of several supported by HTML_QuickForm2. Among others, you can control input lengths, compare the input with some predefined value, and even create your own custom rules using a callback. Consult the HTML_QuickForm2 documentation for the complete details.

Even with the rules added, HTML_QuickForm2 will not actually validate the input until you explicitly call the HTML_QuickForm2 object's validate() method. Therefore, you'll need to add the following code somewhere before the form is rendered:

if ($form->validate()) {
  echo "<p>SUCCESS!</p>";
}


Of course, in a real-world situation you'll want to carry out more than just a simple notification; you likely will add the subscriber's information to a database. However, if the user's input does not meet the validation requirements, HTML_QuickForm2 will notify the user of the problem, as depicted in Figure 4.


Creating Forms with HTML_QuickForm2
Figure 4. Displaying Error Messages

You can easily add CSS to the form, thereby making the error messages quite evident.

Conclusion

HTML_QuickForm2 provides developers with the means for rigorously creating and validating forms in a manner that greatly reduces the likelihood of invalid or harmful input while simultaneously reducing the amount of time and effort needed to develop complex form layouts. Are you using similar utilities that make your programming job easier? Tell us about them in the comments!

About the Author

Jason Gilmore is founder of EasyPHPWebsites.com. He is also the author of several popular books, including "Easy PHP Websites with the Zend Framework", "Easy PayPal with PHP", and "Beginning PHP and MySQL, Third Edition".

Tags: PHP, PHP 5, forms



Page 2 of 2



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Sitemap | Contact Us

Rocket Fuel