cakephp - Cake PHP 2.x model validation returns error on field despite data set
Get the solution ↓↓↓I'm working with a Cake PHP 2 project and am utilising the model validation and have implemented validation into my controller
I've set up my model to contain a$validate
array with my fields and some basic rules, but when validating the request data with thevalidates
method, the validation is failing for some reason.
My model looks ike:
<?php
class MyModelName extends AppModel
{
/*
** Model name
*/
public $name = 'MyModelName';
/*
** Table prefix
*/
public $tablePrefix = 'tlp_';
/*
** Table to save data to
*/
public $useTable = 'some_table';
/*
** Validation
*/
public $validate = array(
'age' => array(
'required' => array(
'rule' => 'required',
'message' => 'This field is required'
),
'numeric' => array(
'rule' => 'numeric',
'message' => 'This field can only be numeric'
)
)
);
}
And then I'm validating like this...
$data = [
'age' => $this->request->data['age'] ?? null,
];
$this->MyModelName->set($this->request->data);
if (!$this->MyModelName->validates()) {
$json['errors'] = $this->MyModelName->validationErrors;
echo json_encode($json);
exit();
}
$hop = $this->MyModelName->save($data);
Why would$this->MyModelName->validates()
always be returning false? I've checked thatage
is in$this->request->data
and it is, and it's absolutely a numeric value.
$this->request->data
looks like the following:
{
"age": 50
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: git was not found in your path, skipping source download
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.