0
votes

I am attempting to manually validate an array from within the model, but validation is successful regardless of what invalid data I populate in the array.

In my CustomerLocation model I am trying to validate $data:

$this->create();
$this->set($data);
if (!$this->validates()){
    //some action if validation fails
}

The $data in this case is a simple array:

Array
(
[location_number] => 125-Knoxville - M
[packing_notes] => Test
[packing_label_message] => packing message
[length] => 4
[width] => 4
[height] => 4
[weight] => 4
[shipping_carrier] => UPS
[shipping_service] => 2nd Day Air
[ship_date] => 
[id] => 768
[row] => 4
)

The $data above contains none of the required fields for the CustomerLocation model, so it should totally fail validation.

The source of this $data is an imported .csv row. When I validate from a baked Cake form for this model, the validation works.

Is my $data array not formatted properly for $this->validates? I would expect it to fail rather than pass if that were the case.

Any advice is certainly appreciated!

2
what are your validation rules? I am pretty sure there's your mistake - mark
Without seeing your validation rules I'm guessing you need to add the 'required' option to your validation rules, which is probably what @mark is getting at. You'll want to read here: book.cakephp.org/1.3/en/view/1145/One-Rule-Per-Field - Joep

2 Answers

1
votes

It turns out I needed to have:

'required' => true

in the validation rules for each field. The notempty rule only applies when Cake is validating from a form, apparently. I should have posted my rules originally. I'm sure someone would have caught that.

0
votes

At a glance, I think you need to change $this->set($data); to:

$this->set(array('CustomerLocation' => $data));

CakePHP uses the first level of the array to determine which model(s) to validate against.

As none of the keys match a model name (ie. you don't have a LocationNumber or PackingNotes model), no validation rules are being found or applied.