Reputation: 850
I am trying to validate an associative array pushed from my JavaScript, using the validation library.
The following code is working except it is only validating (finding the values) for the last array within the associative array, is there a way for it to work for each instance of the array as it runs in the foreach?
code:
if (!empty($JSON)) {
foreach ($JSON AS $k => $data) {
foreach ($data AS $key => $value) {
$this->form_validation->set_data($data);
if($key == 'itemCode' . $k){
$this->form_validation->set_rules($key, 'Item Code', 'required');
}
if($key == 'Desc' . $k){
$this->form_validation->set_rules($key, 'Description', 'required');
}
if($key == 'Qty' . $k){
$this->form_validation->set_rules($key, 'Quantity', 'required|numeric');
}
if($key == 'Cost' . $k){
$this->form_validation->set_rules($key, 'Cost', 'required|numeric');
}
}
//$this->form_validation->reset_validation();
}
}
array output:
[0] => Array(
[Counter0] => 0
[itemCode0] => 1
[Desc0] => 1
[Qty0] => 1
[Cost0] => 1
[Total0] => 1
)
[1] => Array(
[Counter1] => 1
[itemCode1] => 2
[Desc1] => 2
[Qty1] => 2
[Cost1] => 2
[Total1] => 4
)
[2] => Array(
[Counter2] => 2
[itemCode2] => 3
[Desc2] => 3
[Qty2] => 3
[Cost2] => 3
[Total2] => 9
)
[3] => Array(
[Counter3] => 3
[itemCode3] => 4
[Desc3] => 4
[Qty3] => 4
[Cost3] => 4
[Total3] => 16
)
Upvotes: 1
Views: 627
Reputation: 5439
The problem is, the set_data function gets called between the set_rules function and according to CI
You have to call the set_data() method before defining any validation rules.
For more information take a look at the documentation
A possible method would be to catch all data and rules in an array
Below is an example how to achieve that, pls keep in mind i haven't tested it because i wrote it here down but you should be able to see the point
$arrValidationData = array();
$arrValidationRules = array();
$arrCatchValidationData = array(
"itemCode" => array(
"label" => "Item Code",
"rules" => "required"
),
"Desc" => array(
"label" => "Description",
"rules" => "required"
),
"Qty" => array(
"label" => "Quantity",
"rules" => "required|numeric"
),
"Cost" => array(
"label" => "Cost",
"rules" => "required|numeric"
),
);
if (!empty($JSON)) {
foreach ($JSON AS $k => $data) {
foreach ($data AS $key => $value) {
$keyToCatch = str_replace($k, "", $key);
if (isset($arrCatchValidationData[$keyToCatch]))
{
$arrValidationData[$key] = $value;
$arrValidationRules[] = array(
"field" => $key,
"label" => $arrCatchValidationData[$keyToCatch]['label'],
"required" => $arrCatchValidationData[$keyToCatch]['rules']
);
}
}
//$this->form_validation->reset_validation();
}
$this->form_validation->set_data($arrValidationData);
$this->form_validation->set_rules($arrValidationRules);
}
update: 30.05.2016
according to your comment you want to validate post and json data in the same call, in this case you simply have to merge the data
$arrValidationData = array_merge($arrValidationData, $_POST);
Upvotes: 2