Recently, I encountered an issue while trying to validate an optional field for which I defined multiple validation rules. It’s one of those issues I call a bug whereas for the core developers it is a feature…

Let’s say we have an optional “nickname” field. Its value must either be empty or an alphanumeric string with a length between three and ten characters. We start with defining the validation rules:

public $validate = array('nickname' => array('length' => array('rule' => array('between', 3, 10)),
		                             'alpha' => array('rule' => array('alphaNumeric'))));

Those rules work fine. The only “problem” is that they reject an empty string as invalid. To allow an empty string we have to set the option “allowEmpty” to true. So the $validate array is now:

public $validate = array('nickname' => array('length' => array('rule' => array('between', 3, 10)),
		                             'alpha' => array('rule' => array('alphaNumeric')),
				             'allowEmpty' => true));

It looks correct, but as you might guess, it doesn’t work. An empty string still doesn’t pass the validation.

The problem is that “allowEmpty” has to be set on the first rule and not as a setting for the field. And so we have to change the $validate array to:

public $validate = array('nickname' => array('length' => array('rule' => array('between', 3, 10), 'allowEmpty' => true),
		                             'alpha' => array('rule' => array('alphaNumeric'))));

With this solution, an empty string is accepted as a valid value. It’s not really logical, but it works ;-)