CodeIgniter – Form Validation and Optional Fields

I’ve been doing a bit of work lately with CodeIgniter.  It’s been OK but the framework seems quite wrong in most places.  My main gripe is that the “helpers” define themselves as functions in the global namespace (rather than as objects that hook into the CodeIgniter object) which results in some stupidity like a function called “set_value” which just happens to retrieve the value as validated by the form validation “helper”.  Anyway, that’s a lesson learnt.

I’ve been trying to get the form validation to allow me to use set_value for fields that aren’t required, but unless your rules specify the field and a validation rule for it the value won’t be available when set_value is called.  The trick here is to use “echo” as the rule which means that the validation passes and you get back what you put in.  This is not documented in the CodeIgniter manual (it’s implied by the fact that you can use any PHP function as a “rule”).

Example:

$rules = array(
  array(
    'field' => 'name',
    'label' => 'Name',
    'rules' => 'required'
  ),
  array(
    'field' => 'nickname',
    'label' => 'Nickname',
    'rules' => 'echo'
  )
);
 
$this->form_validation->set_rules( $rules );

In this case any calls to set_value(‘nickname’) will return the correct value, rather than an empty string.

2 Comments

  • By Stephane Theroux, April 22, 2010 @ 12:08 pm

    Thanks so much for this workaround. I spent the better part of an hour trying to find the problem in my code.

  • By Tahsin Hasan, October 11, 2010 @ 1:32 am

    Hi,

    see the validation library error fixes on tahsin’s garage

Other Links to this Post

RSS feed for comments on this post. TrackBack URI

Leave a comment

WordPress Themes