bsod99
bsod99

Reputation: 1297

call_user_func() to validate array values

I want to preset validation rules for fields via an array, such as:

$vals = array(
   'val1' => array(
       'rule' => 'ctype_alnum',
   ),
   'val2' => array(
       'rule' => 'ctype_digit',
   ),
);

These fields will be imported from a CSV and inserted into the database if they meet basic validation.

E.g

$while ($data = fgetcsv....)

$array['val1'] = $data[2];
$array['val2'] = $data[9];
$array['val3'] = $data[11];

What I want to do, and I'm not sure how to do this exactly, is now cross reference the $array array with the preset rules in the $fields array. If any of the fields don't validate then the import will be aborted for this row.

Any ideas how to do this?

Upvotes: 2

Views: 136

Answers (2)

Mike Purcell
Mike Purcell

Reputation: 19989

The problem I see, is that you have to determine how you are going to validate each column, for example, is column 0 being validated as an alphanumeric, or as a digit? Another approach, giving validation context to each column would look like:

$columnsDigit = array(0, 3, 7, 8);
$columnsAlnum = array(1, 2, 4, 5, 6);

$while ($line = fgetcsv....) {

    foreach ($line as $column => $value) {

        if ((in_array($column, $columnsDigit)) && (false === ctype_digit($value))) {
            continue 2;
        }

        elseif ((in_array($column, $columnsAlnum)) && (false === ctype_alnum($value))) {
            continue 2;
        }
    }

    // Do something with your valid line
 }

Upvotes: 1

Michael
Michael

Reputation: 12806

This should be what you need:

foreach ($vals as $key => $rule)
{

  if (function_exists($rule['rule']) && !call_user_func($rule['rule'], $array[$key]))
  {
    continue 2;
  }

}

Upvotes: 1

Related Questions