On Wed, 2003-10-01 at 17:43, Chris W. Parker wrote:
> Hey people.
Hey
[snip]
> 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?
I have done something similar to this in a couple projects and have been
fairly happy with it. Without going into too much detail, I define a few
more array elements and call functions instead of doing everything in a
switch statement.
Instead of a 'type' element, I have 'rules' which is a comma delimited
list of the validation I want it to run on each field. For example,
IsEmail, IsNotBlank, IsPhoneNumber. These correspond to functions of the
same name. The reason I have more than one per field (why not just use
IsPhoneNumber in place of IsNotBlank,IsPhoneNumber?) is so that I can
give more detailed error messages.
I think it is a good idea to move your validation into one place,
whether it be in a switch statement or different functions. Not only
does it save you time, but it keeps your validation consistent across
your application.
- Brad
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php