+ Reply to Thread
Results 1 to 2 of 2

Thread: More efficient PHP form validator?

  1. #1
    phpmain2 is offline x10Hosting Member phpmain2 is an unknown quantity at this point
    Join Date
    Nov 2009
    Posts
    9

    More efficient PHP form validator?

    Hi,

    I am trying to make a more efficient form validator - I no longer want to use the IF...ELSE... to check whether or not fields are correctly filled out. I am currently programming in PHP and thus would really appreciate any suggestions in PHP (JavaScript is alright, I guess - I try not to use a lot of it, though).

    Any free and customizable form validator suggestions? :D

  2. #2
    misson is offline x10 Spammer misson is a jewel in the rough
    Join Date
    Mar 2008
    Location
    Libertatia
    Posts
    2,506

    Re: More efficient PHP form validator?

    Server-side, you could use one of the filter functions. filter_var_array can filter a whole array of data in one call.

    Alternatively, hold verification information (REs, functions) in an ancillary data structure. Loop over the input array, applying the verification info for each input field. This amounts to rolling your own filter_var_array.
    PHP Code:
    define('VRFY_RE'1);
    define('VRFY_FUNC'2);
    ...

    function 
    verify($specs$dfltSpec null) {
        
    $fail = array();
        foreach (
    $_REQUEST as $name => $val) {
            if (isset(
    $specs[$name])) {
                
    $spec $specs[$name];
            } elseif (
    is_null($dfltSpec)) {
                continue;
            } else {
                
    $spec $dfltSpec;
            }
            switch (
    $spec['type']) {
            case 
    VRFY_RE:
                if (! 
    preg_match($spec['pattern'], $val)) {
                    
    $fail[] = array('name' => $name,
                                    
    'value' => $val,
                                    
    'msg' => isset($spec['errmsg']) 
                                             ? 
    $spec['errmsg']
                                             : 
    'Failed to match RE');
                }
                break;
            case 
    VRFY_FUNC:
                if (isset(
    $spec['args'])) {
                    
    $args $spec['args']
                } else {
                    
    $args = array();
                }
                
    array_unshift($args$val);
                if (! 
    call_user_func_array($spec['func'], $args)) {
                    
    $fail[] = array('name' => $name'value' => $val
                                    
    'msg' => isset($spec['errmsg']) 
                                             ? 
    $spec['errmsg'
                                             : 
    "Failed to satisfy function '{$spec['func']}'.");
                }
                break;
                ...
            default:
                throw new 
    InvalidArgumentException("{$spec['type']} is not a valid verification type (trying to verify input '$name').");
            }
        }
        return 
    $fail;
    }

    function 
    validUSPhoneNum($candidate) {
        
    $candidate preg_replace('/\D+/'''$candidate);
        return 
    preg_match('/(1\d{3})?\d{7}/'$candidate);
    }
    function 
    validUKPhoneNum($candidate) {
        
    $candidate preg_replace('/\D+/g'''$candidate);
        return 
    preg_match('/(\+44|0)([1-358-9]\d|60|7[05-9])\d{7,8}/'$candidate);
    }
    $specs = array(
        
    'zip' => array('type' => VRFY_RE'pattern' => '/^\d{5}(?:-\d{4})?/'),
        
    'phone' => array('type' => VRFY_FUNC'func' => 'validUSPhoneNum'),
        ...
    );
    try {
        
    $verifyErrors verify($specs);
    } catch (
    InvalidArgumentException $iae) {
        
    error_log($iae);
        echo 
    "An internal error occurred. Sorry about that; it's been logged, and we'll look into it.";

    As far as JS goes, it's good to verify client-side in addition to server side for usability's sake so the user doesn't have to wait for a message round-trip to learn something's wrong with the form. (JS is also a nicer language that PHP.) There are plenty of articles about this online:
    Just be sure you notify the user of invalid elements by marking them and displaying messages in the page, rather than using an alert. Some of the articles you'll find will make this point, but I want to stress it here. An easy way of marking invalid elements is to add an "invalid" class, which is styled to have (e.g.) a red border. Add a 'blur' event listener to each element so the user doesn't have to submit the form. You can also use input filters to prevent users from typing invalid characters. Alternatively, there are plenty of modules for JS libraries that can validate forms. For examples, see jQuery's Plugins/Validation and Prototoype's JSValidate. Google searches will turn up more.

    See also:
    Last edited by misson; 12-30-2009 at 05:21 PM.
    Be sure to read all pages linked in this post; they have further information that should prove useful. When asking for help, make sure you follow Eric Raymond's and Jon Skeet's guidelines for prompt, accurate responses. Please answer any questions I ask; they're not rhetorical (probably). Any posted code is intended as illustrative example, rather than a solution to your problem to be copied without alteration. Study it to learn how to write your own solution.
    Misson, not Mission.

+ Reply to Thread

Similar Threads

  1. Replies: 14
    Last Post: 06-12-2010, 03:35 PM
  2. HTML & PHP Form
    By YASANI in forum Programming Help
    Replies: 6
    Last Post: 02-05-2009, 03:52 AM
  3. currently have an application pending php
    By biomasti in forum Free Hosting
    Replies: 1
    Last Post: 09-03-2008, 01:58 PM
  4. php contact form in flash not working.
    By eddbrown in forum Free Hosting
    Replies: 2
    Last Post: 08-13-2008, 03:16 PM
  5. PHP Email Form
    By DeadBattery in forum Programming Help
    Replies: 4
    Last Post: 04-01-2008, 05:32 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
x10hosting free hosting for the masses
dedicated servers