Laravel 5.4 "Complex Conditional Validation" - php

I was trying to make a complex validation with a Request file
"algunTexto" => "required" ,
"archivo_texto" => "required_if:algunTexto,si|file|mimes:doc,docx,pages,txt|max:10000" ,
It wasn't working, because the request was returning errors that the file must be "doc, docx, etc." and the input must be a file, so I decided to try adding bail
"archivo_texto" => "bail|required_if:algunTexto,si|file|mimes:doc,docx,pages,txt|max:10000" ,
Now the "doc, docx" error was no longer appearing but the other one that the input must be a file was still there.
I made a research and ended up using this:
$data = $request->all();
$validator = validator($data,
[
'archivo_texto' => 'required_if:algunTexto,si'
]
);
$res = $validator->sometimes('archivo_texto', 'file|mimes:doc,docx,pages,txt|max:10000', function($data){
return $data->algunTexto == 'si';
});
But now, even if the radio button named "algunTexto" equals "si", and I don't upload any file on "archivo_texto", I get no error.
What am I doing wrong?

Now it works with the last attemp I made, I missed these lines:
if($validator->fails()){
return back()->withErrors($validator);
}
I thought that it would return automatically with errors just like a Request does, sorry.

Related

Amazon SP_API POST createReport() responded return Invalid Input

I am trying to create a report so I can import products in bulk. The issue i am facing right now is that whatever I have done always got Invalid input error. It seems very very ambiguous error message I have checked issue here and similar once but unfortunately no solution worked.
So if you check below received error from sp-api
{
"notifications": [],
"text": "{\"message\":\"[400] [{\\\"code\\\":\\\"InvalidInput\\\",\\\"message\\\":\\\"Could not match input arguments\\\"}]\",\"success\":false}"
}
you will notice that it seems there is a mistake with my code regarding datatype(as I understood from error) But I have made sure many times of datatype, even I have wrote data as string[] but honestly it took too much time. Please find my code
$config = new Configuration([
"lwaClientId" => $account_data['lwa_client_id'],
"lwaClientSecret" => $account_data['lwa_client_secret'],
"lwaRefreshToken" => $account_data['lwa_refresh_token'],
"awsAccessKeyId" => $account_data['aws_access_key'],
"awsSecretAccessKey" => $account_data['aws_secret_key'],
"endpoint" => SellingPartnerApi\Endpoint::NA ,
]);
$apiInstance = new SellingPartnerApi\Api\ReportsApi($config);
$body = new SellingPartnerApi\Model\Reports\CreateReportSpecification([
'marketplace_ids' => [$merchant_data['marketplace_ids']],
'report_type' => ReportType::GET_MERCHANT_LISTINGS_ALL_DATA['name'],
]);
try{
$report_id = $apiInstance->createReport($body);
}catch(Exception $e){
return array("message"=>$e->getMessage(),'success'=>false);
}
Btw, I am using this lib https://github.com/jlevers/selling-partner-api
Please note that 3 of CreateReportSpecification parameter are optional (report_options, data_start_time, data_end_time) I didn't passed it at constructor.
Could you please advise what's went wrong with my code? Why I am receiving Invalid Input ??
Thanks in advance
Check that AWS_ENV=PRODUCTION (not SANDBOX)

How to solve Argument 1 passed to CodeIgniter\Validation\Validation::run() must be of the type array or null, object given?

I'm facing a problem while working on file validation in Codeigniter 4. Codes are given below.
Codes in the validation file are:
public $image = [
'image_path' => [
'label' => 'Image',
'rules' => 'uploaded[image_path]|is_image[image_path]|max_size[image_path, 1024]|mime_in[image_path,image/jpg,image/jpeg,image/png]'
]
];
And, codes in the controller are:
if($image->isValid() && !$image->hasMoved()):
if(!$this->validation->run($image, "image")):
$this->session->setFlashdata('image_errors', $this->validation->getErrors() ?? "");
return redirect()->back()->withInput();
endif;
endif;
But whenever I'm trying to run these code, the following error happened:
Argument 1 passed to CodeIgniter\Validation\Validation::run() must be of the type array or null, object given.
Please suggest me possible solution for this.
Thank you.
When we need to validate form in the controller we follow this steps:
use validate() method instead of using $validation property
see Controller Validate Data
set flashdata within recirect()->with() method
see Common functions
if condition syntax should be with brackets { }, use if else endif in view files only (optional).
see Alternate Syntax
It's very important and recommended to read User Guide
if ($image->isValid() && ! $image->hasMoved())
{
if (! $this->validate('image'))
{
return redirect()->back()->withInput()->with('image_errors', $this->validator->getErrors())
}
}
if you want to use validation class just do this
if ($image->isValid() && ! $image->hasMoved())
{
$this->validation->setRuleGroup('image');
if (! $this->validation->withRequest($this->request)->run())
{
return redirect()->back()->withInput()->with('image_errors', $this->validation->getErrors())
}
}
I hope it will work fine with your code.

CakePHP 3 autocomplete AJAX responses

I have been trying to get cakephp to suggest input from data that is from my tables like autocomplete. I've done some reading about how some other people have done this but still can't figure it out. Currently it seems that every time my controller is waiting for an ajax request and it is always false. No errors come up from the console some i'm not sure what i'm doing wrong. I tried removing the if ($this->request->is('ajax')) statement but then I get a error about it cannot emit headers.
Here is my search function in InvoicesController which I have taken code from someone else example but failed to implement it.
public function search()
{
if ($this->request->is('ajax')) {
$this->autoRender = false;
pr('b');
$name = $this->request->query['term'];
$results = $this->Invoices->find('all', [
'conditions' => [ 'OR' => [
'id LIKE' => $id . '%',
]]
]);
$resultsArr = [];
foreach ($results as $result) {
$resultsArr[] =['label' => $result['full_name'], 'value' => $result['id']];
}
echo json_encode($resultsArr);
}
}
And here is my search.ctp
<?php use Cake\Routing\Router; ?>
<?php echo $this->Form->input('id', ['type' => 'text']);?>
<script>
jQuery('#id').autocomplete({
source:'<?php echo Router::url(array('controller' => 'Invoices', 'action' => 'search')); ?>',
minLength: 1
});
</script>
This is my invoice table and the ids are what I want to be suggested from what users type in.
I may not be seeing your exact problem but let me point out a few things I see that might help this issue.
Remove this line. It is not necessary
$this->autoRender = false;
Instead you should be doing this at the end. See using the RequestHandler
$this->set('resultsArr', $resultsArr);
// This line is what handles converting your array into json
// To get this to work you must load the request handler
$this->set('_serialize', 'resultsArr');
This will return the data without a root key
[
{"label":"Label Value"},
{"label":"Another Label Value"}
]
Or you can do it like this
$this->set('_serialize', ['resultsArr']);
This will return data like
{"resultArr":[
{"label":"Label Value"},
{"label":"Another Value"}
]}
Replace your finder query with this.
$resultArr = $this->Invoices->find('all')
->where(['id LIKE' => $id . '%'])
// If you want to remap your data use map
// All queries are collections
->map(function ($invoice) {
return ['label' => $invoice->full_name, 'id' => $invoice->id];
});
It seems to me you might want to review the new cakephp 3 orm. A lot of hard work went into writing these docs so that they could be easily read and relevant. I'm not one to push docs on people but it will save you hours of frustration.
Cakephp 3 ORM documentation
A few minor things I noticed that are also problems.
You never define $id.
You define $name but never use it.
pr is a debug statement and I am not sure why you have it.
Based on your comment, here is an update on ajax detection.
// By default the ajax detection is limited to the x-request-with header
// I didn't want to have to set that for every ajax request
// So I overrode that with the accepts header.
// Any request where Accept is application/json the system will assume it is an ajax request
$this->request->addDetector('ajax', function ($request) {
$acceptHeaders = explode(',', $request->env('HTTP_ACCEPT'));
return in_array('application/json', $acceptHeaders);
});

Add multiple custom messages in Laravel validation

I need to add multiple custom error messages like this and both needs to be displayed as validations messages. I have the following code :
if (!$condition1) {
$error[] = "Condition 1 needs to be satisfied";
$validation = false;
}
if (!$condition2) {
$error[] = "Condition 2 needs to be satisfied";
$validation = false;
}
$validator->setCustomMessages($error);
But here I am getting only one message that is the first one even if it is entering to second condition. I have tried to add $validator->setCustomMessages("Message"); in each of the conditions, but it is also doing the same thing.
Why are you using conditionals for validation?
This is what I use to handle validation for uploading photos in my controller.
You have a custom error message for 'required' and one for 'size' (which refers to the size of the photos array).
To add another custom message, just pipe on another rule and its corresponding error message using dot notation.
Only after all rules are satisfied then the code continues execution.
$this->validate($request,
[
'photos' => 'required|size:4'
],
[
'photos.required' => 'Photos are Required',
'photos.size' => 'You must upload 4 Photos'
]
);
Try to change $validator->setCustomMessages($error); for $validator->getMessageBag()->merge($error);
Now if you do $validator->errors()->getMessages() you must have your array with both errors

Laravel - both input values can't be no how to validate?

I'm using Laravel for a project and want to know how to validate a particular scenario I'm facing. I would like to do this with the native features of Laravel if this is possible?
I have a form which has two questions (as dropdowns), for which both the answer can either be yes or no, however it should throw a validation error if both of the dropdowns equal to no, but they can both be yes.
I've check the laravel documentation, but was unsure what rule to apply here, if there is one at all that can be used? Would I need to write my own rule in this case?
very simple:
let's say both the fields names are foo and bar respectively.
then:
// Validate for those fields like $rules = ['foo'=>'required', 'bar'=>'required'] etc
// if validation passes, add this (i.e. inside if($validator->passes()))
if($_POST['foo'] == 'no' && $_POST['bar'] == 'no')
{
$messages = new Illuminate\Support\MessageBag;
$messages->add('customError', 'both fields can not be no');
return Redirect::route('route.name')->withErrors($validator);
}
the error messge will appear while retrieving.
if you get confuse, just dump the $error var and check how to retrieve it. even if validation passes but it gets failed in the above code, it won't be any difference than what would have happened if indeed validation failed.
Obviously don't know what your form fields are called, but this should work.
This is using the sometimes() method to add a conditional query, where the field value should not be no if the corresponding field equals no.
$data = array(
'field1' => 'no',
'field2' => 'no'
);
$validator = Validator::make($data, array());
$validator->sometimes('field1', 'not_in:no', function($input) {
return $input->field2 == 'no';
});
$validator->sometimes('field2', 'not_in:no', function($input) {
return $input->field1 == 'no';
});
if ($validator->fails()) {
// will fail in this instance
// changing one of the values in the $data array to yes (or anything else, obvs) will result in a pass
}
Just to note, this will only work in Laravel 4.2+

Categories