Laravel Rule:exist() not giving expected behavior - laravel

I want user to provide postal code using input text field and despite of the white spaces he/she uses when providing the postal code I want it to pass validation if it is available in my database so I used the following code in my validator:
'postal_code' =>['required','string','max:7',Rule::exists('zipcodes','POSTAL_CODE')->where(function ($query) use($postalcode) {
return $query->whereRaw('replace(POSTAL_CODE,\' \',\'\')=? ',[str_replace(' ','',$postalcode)]);
})],
]);
but when I test the form I used it for it show error if I input aaa7fr but no error if I used aaa 7fr which is exactly in my database which I do not want and instead I want both to show no error.
Would you please kindly tell me where is the wrong in my code and how to fix it?

Related

How to completely control Laravel Excel customValidationMessages output messages?

I am currently using Laravel Excel to import data from an excel file into database. When there are some errors occur, I'd like it to report in a foreign language rather than in English which I know I have to use customValidationMessages() function to define the output messages.
This is an example of regular messages:
There was an error on row 2. The somefield has already been taken.
There was an error on row 3. The somefield has already been taken.
Which consists of 2 parts
There was an error on row {some_row}. is the first part.
and
The somefield has already been taken. is the last part
and when I follow the document provided here https://docs.laravel-excel.com/3.1/imports/validation.html#custom-validation-messages all I can output in the foreign language is just the last part but the first part remains in English like this.
There was an error on row 2. ข้อความในภาษาต่างประเทศ
There was an error on row 3. ข้อความในภาษาต่างประเทศ
But I want it to be like this
ข้อความภาษาต่างประเทศแถวที่ 2. ข้อความในภาษาต่างประเทศ
ข้อความภาษาต่างประเทศแถวที่ 3. ข้อความในภาษาต่างประเทศ
How can I do it???
Thank you all in advance
after inspect the library source, it looks like they use the laravel's localization for that part too: __('There was an error on row :row. :message', ['row' => $this->row, 'message' => $message]);
https://github.com/SpartnerNL/Laravel-Excel/blob/44e165b73eaf182a2f699d905a20684889675b1c/src/Validators/Failure.php#L82
so you can define your own localization message like: "There was an error on row :row. :message" => "ข้อความภาษาต่างประเทศแถวที่ 2 (change to your own message because I don't really know your language)",

Laravel 5.4 : Dynamic validation rule

I kind of struggle to find the answer to my question, and my test don't prove to be useful. So maybe someone here would have hit the same issue that I'm facing.
I have inputs with the following kind of patterned name projects-0-1, project-0-2, project-1-0 and so on... These are file inputs so people can upload a document/an image.
So basically, I've been trying to get a validation message that would (ideally) be something like that:
$validator->getMessageBag()->add('project-*-*', 'File is empty!');
OR
$validator->getMessageBag()->add('project-*', 'File is empty!');
I tried a couple of things already and nothing seems to work.
The reason I get to add a custom message is that file is simply not validated if it comes empty to the $request object. So I first need to check if the $request->hasFile and in case it doesn't I want to add the error message.
Things to consider:
inputs can be dynamically added to the form, so I don't know the exact number of file inputs I need to validate beforehand.
even if this should not impact the code and validation, it's worth noticing that everything happens through ajax as I embed the form on another website. Therefore I created endpoints etc...
Any hint ?
Right, coming back here in case someone faces that issue too. I found a "hacky" way to get there and it does the trick for me.
As each input file is dynamically added to the DOM, I add an extra hidden input that holds the name of the file input as a value.
Then in my controller I do smth like that:
public function createValuesKeyArray ($preset)
{
$regexPattern = '/^'. $preset .'-[0-9]*$/';
$customPresets = preg_grep($regexPattern, array_keys(Input::all()));
$keys = [];
foreach ($customPresets as $customPreset) {
array_push($keys, $customPreset);
}
return $keys;
}
// This allows me to get all hidden input names in an array in order to get its value from the $request
$hiddenInputs = $this->createValuesKeyArray('hidden-project-name');
Once I get this array, I can do stuff like that and dinamycally add my set of rules for the input files present in the DOM:
foreach($hiddenInputs as $hiddenInput){
$globalRules[$request[$hiddenInput]] = 'required';
}
Not sure if this the right way to get there, but it does the job for me and I don't find that code horrible. I'll stick with it until I find a better way.

Laravel - accessing lang/en/validation.php from test suite

I want to test that warning messages are displayed correctly when form fields are returned as invalid. The best way to do this would be to access the array in validation.php to get the name of the language line that I want to use.
How can I do this?
The documentation for Laravel is very great. You can access language files in resources/lang/{locale}/ easily with the provided trans() function (Laravel 5):
$expected = 'The :attribute may only contain letters.';
$actual = trans('validation.alpha');
$this->assertEquals($expected,$actual);
Please provide your attempts in the question next time. Also have a look at the SO tour (you will be rewarded with a bronze badge afterwards!)

"field was not set" instead of specific error message in codeigniter

I am using codeigniter form validation rules.Instead of showing me correct error message it is showing "Field was not set". I want to show error related to field name.
This is my code.
$this->form_validation->set_rules('project_name', 'Project Name', 'trim|required');
how to show that "Firstbane is required" or something default of codeigniter.
Thanks in advance!
I had the same problem.
I solved it as follow:
I have "xampp" installed, with the option "short_open_tag=false" in the "php.ini" file. I have the package of spanish language installed, too. This one have "validation_lang.php" file in the path "system/laguage/spanish" (I'm Spaniard) and it start with "<?" short tag. Well, I changed the "<?" by "<?php". Later, my program worked.
I hope it can help you.
Excuse me my bad English!
You can set a custom error message with set_message and use the label from the set_rules function. You can find the documentation here.
Here is an example:
// Set the validation rule
$this->form_validation->set_rules('project_name', 'Project Name', 'trim|required');
// Set the custom message with %s where the label should go
$this->form_validation->set_message('required', '%s is required. Please enter a value.');
// For an invalid project_name, you will get the error:
// Project Name is required. Please enter a value.
In my case user3110655, I got the same issue when using another language than english with system language files downloaded over the web.
All files were good, except form_validation one.
Keys wasn't written like the english file and tag wasn't with %s as expected.
If using a language file, double check that your file is correctly written like the english one provided by code igniter.

Codeigniter form validation, custom check doesn't work if the field is not required

Gah.. I have spent way to long on this, but I believe I have found the problem.
Essentially I have a hidden field which is populated when a user clicks on an image.
It is required that the user has clicked the image but I do not want the generic form error message for a 'required' check with the CI form validation class.
As such I quickly made a image_required function in my extended form validation class, and set a rule such that this rule was applied to the hidden field.
function image_required($str)
{
$CI =& get_instance();
$CI->form_validation->set_message('image_required','Please click the image above.');
if($str != '')
{
return TRUE;
}
else
{
return FALSE;
}
}
If the hidden field was blank no error was being called.
I am led to believe now that this is because CI says this field is empty yet it is not 'required', therefore we will ignore all the other validation rules for the field. Is this correct?
If so how can i go about requiring this field be set but having a custom error message?
bangs head
Thanks
If you look at the source code (v2.1.3) for the '_execute' routine (system/libraries/Form_validation.php) you will see on line 486
// If the field is blank, but NOT required, no further tests are necessary
So you are correct, it needs to be required and then it will process your rule.
In order to fix it so you can have a non-required blank field that still processes rules, you should override the '_execute' method by creating a file called 'MY_Form_validation.php' in the application/libraries folder (I think, you might need to check exactly how you extend an existing library) and then copy the '_execute' method and alter the code to continue on a non-required but blank entry.
I do love CI, but I have to say this does not allow the flexibility required. It is perfectly reasonable to have a field that cannot be empty, but is NOT required. As in, you wouldn't enforce "user MUST enter a value", but they cannot submit a blank. I think someone got confused between EMPTY and REQUIRED.
1) REQUIRED: User MUST put a value in the field and it cannot be empty (i.e. '')
2) EMPTY: User does not HAVE to enter a value, BUT, if they do, it's cannot be empty. This not the same as REQUIRED... Looks like I'll be using a callback again.
REQUIRED incorporates two logical steps (1->Must enter a value, and 2->Cannot be empty) these two steps should be separated logically to allow either / or.
In constraint terms it would be either, REQUIRED, NOT NULL. Or NOT REQUIRED, NOT NULL.

Resources