Welcome Guest, Not a member yet? Register   Sign In
Bug. Form validation fails if form array element is empty
#2

[eluser]Unknown[/eluser]
I was fighting with this problem, and I think I figured it out.

In the Form_validation library, each field's postdata – $this->_field_data[$field]['postdata'] – is initialized to NULL when set_rules() is called. Subsequently, when _execute() is called on the field, there's a check to determine whether the field is required, so that it can bail out early for empty fields. The check assumes that blank fields will evaluate to NULL:

Code:
482. // If the field is blank, but NOT required, no further tests are necessary
483. $callback = FALSE;
484. if ( ! in_array('required', $rules) AND is_null($postdata))

But if a field contains an array of values, when _execute() is called recursively on each one $postdata is no longer NULL. In the case of an empty field, the $val passed to the recursive call is an empty string.

As a quick fix, I extended the Form_validation library to nullify empty $postdata values before the _execute() function gets ahold of them:

Code:
class MY_Form_validation extends CI_Form_validation {
  function __construct()
  {
    parent::__construct();
  }
  public function _execute($row, $rules, $postdata = NULL, $cycles = 0)
  {
    if (empty($postdata)) $postdata = NULL;
    return parent::_execute($row, $rules, $postdata, $cycles);
  }
}

A better fix might be to change line 484. to use empty() instead of is_null():

Code:
484. if ( ! in_array('required', $rules) AND empty($postdata))

I have no idea how to submit a patch, but I'll try to figure out how now, in case this is actually useful :-)


Messages In This Thread
Bug. Form validation fails if form array element is empty - by El Forum - 10-25-2010, 11:41 AM



Theme © iAndrew 2016 - Forum software by © MyBB