CodeIgniter the way to validate form data without callbacks

Go To StackoverFlow.com

0

I got the following array in my config file:

$config['reg_datas'] = array(
    'high' => array(
        7  => 200,
        30 => 500
    ),
    'box' => array(
        7   => 125,
        30  => 350
    ),
    'shots' => array(
        7   => 25,
        30  => 50
    )
);

So, referring to CI's manual, I'm validating my form data using this validation rule: callback__validate_high... and I have to use this callback function:

public function _validate_high($input)
{
    $cfg = $this->config->item('reg_datas');
    if ( !array_key_exists($cfg['high'], $input)
    {
        $this->form_validation->set_message('_validate_high', 'Invalid High Field...');
        return FALSE;
    }

    return TRUE;
}

The question is; do I really have to create a new callback everytime I need to check, if array_key_exists ? The above code is just one validation rule (for one array), but there are 3 arrays in my config file (and probably soon there will be some more) - so I really will have to create 3 callback functions for such simple check?

CodeIgniter is my first framework I'm learning, and want to learn it as best as it's possible for me, and I really care about such thing because I simply don't want to waste my time.

2012-04-05 01:23
by Cyclone


1

First, your syntax for array_key_exists() is wrong, key is first attribute and array second. Like this: array_key_exists($input, $cfg['high']);.

And for validation, make a common function instead of checking key one by one. Also put error codes on config file.

$config['reg_datas_error'] = array(
  'high' => 'Invalid High Field',
  'box' => 'Invalid box Field',
  'shots' => 'Invalid Shots Field'
);

And you common validation function

public function _validate_field($input, $key)
{
   $cfg = $this->config->item('reg_datas');
   $cfg_error = $this->config->item('reg_datas_error');
   if ( !array_key_exists($input, $cfg[$key])
   {
      $this->form_validation->set_message('_validate_'.$key, $cfg_error[$key]);
      return FALSE;
   }

   return TRUE;
}

Note that these are just example, you improve or do another way. Just main logic how to do general validation

2012-04-05 05:38
by safarov
Oh, I didnt knew that I can use more than one parameter in the callback function! Thanks - Cyclone 2012-04-05 10:11
Ads