Re: need to convert field names into array for form submission

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Hello Bruce,

Friday, August 12, 2005, 1:39:54 PM, you wrote:
> I believe this can be done with an array.
> any assistance is greatly  appreciated!

I've been working on a validation function for quite a while now that
does what you're asking. I keep adding to it as I run across stuff I
didn't need before. It's not perfect, but it does work pretty good. It
does not do addslashes() because I do that only when I need to store
it in a DB.

Ok... Let's see if I can put this together without it being too ugly.

The function as functions.php:
*********************************************************************
function validate($fieldName, $value, $size, $type, $extra="0")
{
  GLOBAL $errors;
  GLOBAL $safe;
  
  if ($value != "")
  { 
    switch ($type) 
    {
      case 'alpha': #Matches only letters and a hyphen (for last names)
        if (!preg_match("/^[a-z]+-?[a-z]+$/i", $value))
        {
          $errors[0] = 1; 
          $errors[$fieldName] = '<span class="badnote">This field only accepts alphabetic input';
        }
        break;
//------------------------------------------------------------------------------
      case 'numeric': #Matches numeric input
        if (!preg_match("/^[0-9\.]+$/", $value))
        {
          $errors[0] = 1; 
          $errors[$fieldName] = '<span class="badnote">This field only accepts numeric input';
        }
        break;
//------------------------------------------------------------------------------
      case 'phone': #Matches phonenumber in xxx-xxx-xxxx where area code and exchange do not start with a "1" 
        if (!preg_match("/^[2-9][0-9]{2}-[2-9][0-9]{2}-[0-9]{4}$/", $value))
        {
          $errors[0] = 1; 
          $errors[$fieldName] = '<span class="badnote">Phone number must be in xxx-xxx-xxxx format';
        }
        break;
//------------------------------------------------------------------------------
      case 'email': #Should match 99% of valid e-mail addresses
        if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $value)) 
        {
          $errors[0]= 1; 
          $errors[$fieldName] = '<span class="badnote">E-mail address ' . $email . ' doesn\'t appear valid, please verify';
        }
        break;
//------------------------------------------------------------------------------
      case 'alphanumeric': #Matches strings with only alphanumerics
        if (!preg_match("/^[0-9a-z]+$/i", $value))
        {
          $errors[0] = 1; 
          $errors[$fieldName] = '<span class="badnote">This field only accepts alphanumeric characters';
        }
        break;
//------------------------------------------------------------------------------
      case 'descriptor':  #Allows strings with alphanumerics, and other common
                          #things you'd find in titles and descriptions
        $value = htmlentities($value);
        break;
//------------------------------------------------------------------------------
      case 'date': #Matches strings with dates as mm-dd-yyyy    
        if (!preg_match("/^(0[1-9]|1[012])\/(0[1-9]|[12][0-9]|3[01])\/(19|20)\d\d$/i", $value))
        {
          $errors[0] = 1; 
          $errors[$fieldName] = '<span class="badnote">Invalid date, enter as mm/dd/yyyy';
        }
        break;
//------------------------------------------------------------------------------
      case 'time12': #Matches strings with dates as hh:mm
        if (!preg_match("/^([0]?[1-9]|1[0-2]):[0-5][0-9]$/i", $value))
        {
          $errors[0] = 1; 
          $errors[$fieldName] = '<span class="badnote">Invalid time, enter as xx:xx';
        }
        break;
//  ------------------------------------------------------------------------------
      case 'lat': #Matches strings with latitude as hddd mm.mmm 
        if (!preg_match("/^-?([0-8]{1,3})\s([0-9]{1,2})\.[0-9]{1,3}$/",$value))
        {
          $errors[0] = 1; 
          $errors[$fieldName] = '<span class="badnote">Invalid value, enter as ddd mm.mmm';
        }
        $value = str_replace(".", "", $value);
        $value = str_replace(" ", ".", $value);
        if ($extra == "S")
          $value = "-" . $value;
        break;
//  ------------------------------------------------------------------------------
      case 'long': #Matches strings with longitude as hddd mm.mmm 
        if (!preg_match("/^-?([0-9]{1,3})\s([0-9]{1,2})\.[0-9]{1,3}$/",$value))
        {
          $errors[0] = 1; 
          $errors[$fieldName] = '<span class="badnote">Invalid value, enter as ddd mm.mmm';
        }
        $value = str_replace(".", "", $value);
        $value = str_replace(" ", ".", $value);
        if ($extra == "W")
          $value = "-" . $value;
        break;
//------------------------------------------------------------------------------      
    }
    //Common to all in switch
    if (strlen($value) > $size)
    {
      if (!isset($errors[$fieldName]))
        $errors[$fieldName] .= '<span class="badnote">';
      else
        $errors[$fieldName] .= '<br />';
    
      $errors[0] = 1; 
      $errors[$fieldName] .= 'Field limited to ' . $size . ' characters';
    }
    if (isset($errors[$fieldName]))
      $errors[$fieldName] .= '</span>';
  } //Ends if on a blank value
  else
  {
    $errors[0] = 1;         
    $errors[$fieldName] = '<span class="badnote">You can not leave this field blank</span>';
  }
  //It passed all the tests and is considered safe. Use this array to echo output
  //to the user or to insert / update a DB field.
  if (!isset($errors[$fieldName]))
    $safe[$fieldName] = stripslashes($value);
}
*********************************************************************


The validator.php file:
*********************************************************************
require_once('functions.php');

validate('waypointID', $_POST['waypointID'], 6, 'alphanumeric');
validate('waypointName', $_POST['waypointName'], 50, 'descriptor');
validate('datePlaced', $_POST['datePlaced'], 10, 'date');
validate('lat', $_POST['lat'], 10, 'lat', $_POST['latComp']);
validate('long', $_POST['long'], 10, 'long', $_POST['longComp']);
validate('placedBy', $_POST['placedBy'], 50, 'descriptor');
validate('waypointType', $_POST['waypointType'], 25, 'descriptor');
validate('waypointSize', $_POST['waypointSize'], 25, 'descriptor');
validate('terrain', $_POST['terrain'], 3, 'numeric');
validate('difficulty', $_POST['difficulty'], 3, 'numeric');
*********************************************************************

You can see from the use as follows:

validate(
A name you'll use for this item in the array,

The source of the thing you're validating,

The max size in chars for it,

The type of validation you want done,

"extra" you can see used in the lat and long for N,S,E,W but can be
used in other validation cases when needed.
)

validator.php gets included if ($_POST['submit'] == 'submit')

To show errors, I do this:
*********************************************************************
<tr><td>Waypoint ID</td><td><input type="text" name="waypointID" style="width: 187px;" value="<?php echo $_POST['submit'] == "Submit" ? $safe['waypointID'] : 'GCXXXX';?>" />&nbsp;&nbsp;<?php echo $errors['waypointID'];?></td></tr>
*********************************************************************

The $errors[] and $safe[] key is created via the first variable in the
validate() function.

I don't do anything with the input (write to file/DB)
if $errors[0] == 1;

But if there are no errors, I use the validated ($safe[]) input like:
$gpxOutput .= '<keywords>' . $safe['keywords'] . ', devtek</keywords>' . "\r\n";

The CSS class "badnote" is just red text in a slightly smaller font
size.

You can see how the whole thing works (the example is from a GPX XML
generator I just wrote) at:

http://www.pcwize.com/geocaching/gpx_generator.php

If you want the code for it to see it all working together, let me
know as I'll be GPL'ing it when I'm done.

-- 
 __    ____  ____  ____   TBUDL/BETA/DEV/TECH Lists Moderator / PGP 0x6C0AB16B
(  )  ( ___)(_  _)( ___)  TBUDP Wiki Site:  http://www.PCWize.com/thebat/tbudp
 )(__  )__)  _)(_  )__)   Roguemoticons & Smileys:    http://PCWize.com/thebat
(____)(____)(____)(__)    PHP Tutorials and snippets:    http://www.DevTek.org

Serial killer strikes!  Mouse and modem found dead.

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux