views:

305

answers:

4

Hello,

I am currently trying to validate a form server side, the way it works is all the data is put into and array, with the form field as the key and and the field data as the value, however I need to check that all the keys have a value associated with other wise I want the submittion to stop and the user having to edit there details and then re-submit, is there a quick check I can run rather that break the array apart and check that or check before it is put in the array with a switch or losts of if statements?

A: 

Hi,

How about something like

<?php
$arrayFilled = true;
foreach($array as $key=>$value) {
    $arrayFilled = trim($value) == '' ? false : $arrayFilled;
    if($arrayFilled === false) { break; }
}
if($arrayFilled === false) {
    echo "missing data";
}
else {
    echo "filled array";
}

you may want to check for more than just an empty string but I'll leave that to you

Anthony
Could you tab your lines?
Jonathan Sampson
Meh! didn't press space enough times ...
Anthony
@Anthony - Thanks, man :) Cleaner code = Happier Readers.
Jonathan Sampson
+1  A: 

Sico87,

More of than not you don't want to test all of the fields simultaneously. For instance you may have a contact field that contains a phone-number entry option that isn't mandated, and rejecting the submission for that reason would be problematic.

In many cases, it's easier to test your fields individually so you can give each the special attention it needs. You'll want to give special attention to email addresses, and special attention to birthdays.

Treating all equal could cause very serious problems in the long-run.

Jonathan Sampson
+1  A: 
function fieldEmpty($value) {
    return trim($value) == '';
}

if (count(array_filter($array, 'fieldEmpty'))) {
    die('bad');
}
Tom Haigh
A: 

One option is to do a bit of both.

Have a separate array of field options with the field name as the key.

$fieldTypes = array('nameFirst' => 'name',
                    'nameLast'  => 'name',
                    'phone'     => 'phone',
                    'email'     => 'email');
foreach($input as $key => $value) {
    switch($fieldTypes[$key]) {
        case 'name':
            //run $value against name validation
            break;
        case 'phone':
            //run $value against phone validation
            break;
        case 'email':
            //run $value against email validation
            break;
        default:
            //code here for unknown type
    }
}

Now, that could be used in any number of ways, and easily expanded to include things like if the field is required or not, or even error messages. By turning the $fieldTypes array into a multidimensional array, or an array of objects containing the data.

This way, if you decide to add a field, it would probably not involve much change in the validation code.

J. Kenzal Hunter Sr.