PHP
  Home arrow PHP arrow Page 11 - Building An Extensible Form Validator ...
Dev Shed Forums 
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Sun Developer Network 
Dedicated Servers 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Actuate Whitepapers 
VeriSign Whitepapers 
VPS Hosting 
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PHP

Building An Extensible Form Validator Class
By: icarus, (c) Melonfire
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 39
    2002-03-27

    Table of Contents:
  • Building An Extensible Form Validator Class
  • Back To Class
  • The Bare Bones
  • How Things Work
  • Private Eye
  • Running On Empty
  • Floating Like A Butterfly
  • Mail Dot Com
  • Under Construction
  • A Quick Snack
  • Going To The Source
  • Closing Time

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT

    Stay one step ahead of the competition. Evaluate and give feedback on some of the hottest web development tools on the market today. Make your opinion heard! Click Here

    Building An Extensible Form Validator Class - Going To The Source


    (Page 11 of 12 )

    Of course, this is just my first stab at a generic form validation class. It's designed for very simple requirements, and may be way too primitive for your requirements. If this is the case, you have two basic options:

    1. File the results of my efforts in the trash can and write your own, much-cooler, does-everything-but-make-toast class;

    2. Pick up a free, open-source PHP class which offers a more powerful feature set.

    If you picked door one, you don't really need my help any more. You can stop reading right now and get to work. Have fun, and remember to send me a Christmas card if you sell your software for a million bucks.

    If, on the other hand, you're lazy and figured that door two was more promising, you'll be happy to hear that the Web has a huge number of powerful form validation classes floating around it, many of them extremely powerful. Here are two that looked particularly interesting:

    Manuel Lemos' form class allows you to programmatically construct HTML forms, offering extremely powerful client- and server-side validation features to make your forms as bulletproof as possible. The class is freely available at http://www.phpclasses.org/browse.html/package/1, and comes with excellent documentation and examples.

    Here's an example of a simple online form created with this class:

    <html> <head><basefont face="Arial"></head> <body> <?php // function to output form // called by class Output() method function displayForm($str) { echo $str; } // include class include("forms.php"); // instantiate object $contact = new form_class; // set some form properties $contact->NAME="contact"; $contact->METHOD="POST"; $contact->ACTION=$PHP_SELF; // start building the form fields // add a name field $contact->AddInput(array( "TYPE"=>"text", "NAME"=>"name", "MAXLENGTH"=>50, "ValidateAsNotEmpty"=>1, "ValidateAsNotEmptyErrorMessage"=>"You must enter your name" )); // note that you can specify how to validate the data while adding a field // a number of different validation routines are available // look at the documentation for details // add an email address field $contact->AddInput(array( "TYPE"=>"text", "NAME"=>"email", "MAXLENGTH"=>150, "ValidateAsEmail"=>1, "ValidateAsEmailErrorMessage"=>"You must enter a valid email address", )); // add a textarea box for message $contact->AddInput(array( "TYPE"=>"textarea", "NAME"=>"message", "ROWS"=>6, "COLS"=>40, "ValidateAsNotEmpty"=>1, "ValidateAsNotEmptyErrorMessage"=>"You must enter a message", )); // and so on // you can also add radio buttons, list boxes and check boxes // add a submit button $contact->AddInput(array( "TYPE"=>"submit", "NAME"=>"submit", "VALUE"=>"Send Message" )); // check to see if the form has been submitted // use the form variable "submit" as the key if ($contact->WasSubmitted("submit")) { // if form has been submitted // read in all the form data $contact->LoadInputValues(TRUE); // validate the data on the server-side again // invalid fields are stored in the array $invalid[] // the first error message is stored in $error $error = $contact->Validate(&$invalid); if ($error != "") { // if error, report it echo "The following error occurred: $error"; } else { // else mail the form data to the webmaster // and report result echo "Your message was successfully sent."; } } else { // form not yet submitted // so display it to the user // begin constructing the form // using the field definitions above // note how AddDataPart() can be used to intersperse // HTML code between the form fields $contact->AddDataPart("<br> Name: <br>"); $contact->AddInputPart("name"); $contact->AddDataPart("<br> Email address: <br>"); $contact->AddInputPart("email"); $contact->AddDataPart("<br> Message: <br>"); $contact->AddInputPart("message"); $contact->AddDataPart("<br>"); $contact->AddInputPart("submit"); } // all done // now output the form/form result // this function dumps the HTML form (or its result) // together with all required JavaScript code $error = $contact->Output(array( "Function"=>"displayForm", "EndOfLine"=>"\n" )); // end ?> </body> </html>
    As you can see, Lemos' class exposes a number of methods to dynamically construct form elements, and to apply validation rulesets to them. These form elements can then be printed to the browser, and the data entered into the form can be validated using the built-in client-side and server-side validation functions.

    If you're looking for something a little simpler, consider David Tufts' validation class, which provides a an easy-to-use, albeit primitive, form validation API that would probably be best suited to smaller applications. This class is available online at http://dave.imarc.net/php.php

    Here's an example of a simple online form created with this class:

    <html> <head> <basefont face=Arial> </head> <body> <?php if (!$submit) { ?> <form action="<?=$PHP_SELF?>" method="POST"> Name: <br> <input type="text" name="name" size="30"> <p> Email address: <br> <input type="text" name="email" size="30"> <p> Message: <br> <textarea name="message" cols="45" rows="6"></textarea> <p> <input type="submit" name="submit" value="Send"> </form> <?php } else { // include class include("form_validator.class"); // instantiate object $fv = new form_validator(); // specify fields to be checked // these fields are only checked to ensure that they contain values // advanced data type validation is not possible if ($fv->validate_fields("name, email, message")) { // if no errors // send out mail // report status echo "Your message was successfully sent."; } else { // or list errors echo "The form could not be processed because the following fields contained invalid data:"; echo "<ul>"; foreach ($fv->error_array as $e) { echo "<li>$e"; } echo "</ul>"; echo "Click <a href=javascript:history.back()>here</a> to go back and correct the errors"; } } ?> </body> </html>
    Short and very sweet - and perfect for applications that don't require advanced data validation!

    More PHP Articles
    More By icarus, (c) Melonfire


     

       

    PHP ARTICLES

    - Viewing and Editing Tasks for a Project Mana...
    - More on Private Methods with PHP 5 Member Vi...
    - Adding Tasks to a Project Management Applica...
    - Utilizing Private Methods with PHP 5 and Mem...
    - Making Changes in a Project Management Appli...
    - Defining Public and Protected Methods with M...
    - HTML for a Project Management Application
    - Using Subclasses and Accessors with Member V...
    - Implementing Internet Protocols with PHP
    - Project Management: The Application
    - Working with Private Properties to Protect P...
    - Protecting PHP 5 Class Data with Member Visi...
    - Setting Up a Web-based Image Hosting Service
    - Comparing Files and Databases with PHP Bench...
    - Setting Up a Web-Based Image Gallery





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 5 hosted by Hostway