Reputation: 347
I am using some simple validation on my town/city fields in my database. This has been applied in the models. As you can see both fields, city and town, require a minimum length of 3 characters and cannot be empty.
However when people fill in the form for this field they will have a town or a city, not both. How do I create a check in the validation so that only 1 of these fields has to be completed? I obviously cannot 'allowEmpty' => true for both fields so how do I implement this?
THe validation rules:
'town' => array(
'rule' => array('minLength', 3),
'allowEmpty' => false,
'message' => 'Must have town'
) ,
'city' => array(
'rule' => array('minLength', 3),
'allowEmpty' => false,
'message' => 'Must have city'
) ,
Any suggestions?
Upvotes: 0
Views: 623
Reputation: 7882
You can create a custom validation rule on your AppModel, something like this:
function eitherOr(&$data, $orFields = array()) {
foreach ($orFields as $orField => $orValue) {
if (!empty($orValue)) {
unset($this->validationErrors[key($data)]);
}
}
return true;
}
Then, add to your validation rules.
var $validate = array(
'town' => array(
'empty' => array(
'rule' => 'allowEmpty'
),
// other rules
),
'city' => array(
// other rules
'eitherOr' => array(
'rule' => array('eitherOr', array('town'))
)
)
);
Basically, it will check for a value from the array of fields you pass in the second param (in this case, array('town')
would check the town field. If the value is not empty, it will remove any validation errors on city and therefore allow it to pass. The rule needs to go last so validation errors are removed.
Upvotes: 1