your method for validating forms
| From: | Chris W. Parker | Date: | Wed, 01 Oct 2003 23:43:23 +0000 |
| Subject: | your method for validating forms | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-164646@lists.php.net to get a copy of this message | ||
Hey people.
I'm trying to come up with an easy way to validate forms. I've got an
idea and I'd like your feedback as well as suggestions and/or your own
methods.
My idea is to have a multi-dimensional array with fields: data and type.
Let's say you have a form with three fields. First Name (fname), Last
Name (lname), and Phone Number (phone). It's sent to a processing script
via GET. On the processing script you have the basics:
<? // pseudo code
// collect data
$fname = (!empty($_GET['fname'])) ? $_GET['fname'] : "" ;
$lname = (!empty($_GET['lname'])) ? $_GET['lname'] : "" ;
$phone = (!empty($_GET['phone'])) ? $_GET['phone'] : "" ;
// validate data
if($fname is not [a-zA-Z]{2,20})
{
// mark as error
}
if($lname is not [a-zA-Z]{2,20})
{
// mark as error
}
$phone = stripOutEverythingButTheNumbers($phone);
if($phone is not [0-9]{10}) // we only sell to US via website
{
// mark as error
}
$_SESSION['form_errors'] = put_the_errors_in_here;
redirect("to_the_previous_page.php"); // where the errors will be read
// and the fields with bad data
// will be marked appropriately
?>
What I'd like to do is get rid of all the if's and what not and throw
them into a function. What I thought of doing to replace all this is:
<? // pseudo code
$formdata['fname']['data'] = (!empty($_GET['fname'])) ?
$_GET['fname'] :
"" ;
$formdata['fname']['type'] = "name";
$formdata['lname']['data'] = (!empty($_GET['lname'])) ?
$_GET['lname'] :
"" ;
$formdata['lname']['type'] = "name";
$formdata['phone']['data'] = (!empty($_GET['phone'])) ?
$_GET['phone'] :
"" ;
$formdata['phone']['type'] = "phonenumber";
$_SESSION['form_errors'] = validateFormData($formdata);
redirect("to_the_previous_page.php");
?>
The validateFormDate() function would be defined something like this:
function validateFormData($input)
{
foreach($input as $field)
{
switch ($field['type'])
{
case 'name':
// do the magic
break;
case 'phonenumber':
// do the magic
break;
}
}
}
The validateFormData() function will return false if there are no errors
to report.
For a form that has a lot of fields to validate I think this can make
things pretty easy.
So... what do you think?
Chris.