Laravel Request Validation Regex without Required - php

I have a problem with Request validation. Everything works but one pattern. And its if I dont want the field to be required but once it is filled I want it to match a regex.
But it throws regex error when I leave the field empty.
Any tips on how I should handle it?
BTW: I made a custom Request class where I take care of the validation so if the solution could be also in the Request and not directly in Controller that would be great.
return [
'dic' => 'max:12|regex:/^[a-zA-Z]{2}[0-9]{8}[0-9]*$/',
];

return [
'dic' => 'nullable|max:12|regex:/^[a-zA-Z]{2}[0-9]{8}[0-9]*$/',
];
nullable won't check the other rules when the field is empty.

Related

Laravel Validation: bail rule not working

According to Laravel Documentation, bail rule should stop running validation rules after first validation failure.
I have a file outside App\Http\* namespace with the following code in it:
if(Validator::make($params, [
'email' => 'bail|required|email|max:60|exists:customers,email',
'password' => 'required|max:60|string',
'password' => new CustomerCheckPassword($params['email']),
]) -> fails())
throw new Exception('message here');
Works like a charm, except bail rule from email attribute does not stop the validation when $params['email'] is not contained by customers.email, and goes on to password as well. Do you have any ideas or elegant workarounds for this issue?
In a different section of the same docs page (it won't link directly to it), it explains that bail only applies to the current attribute. So for instance, if email is missing, it will not check anything after required, but password is a new attribute so it will validate it as normal.
Sometimes you may wish to stop running validation rules on an attribute after the first validation failure. To do so, assign the bail rule to the attribute:
One way to accomplish this would be to use the sometimes method
Validator::make($params, [
'email' => 'bail|required|email|max:60|exists:customers,email',
'password' => 'required|max:60|string',
])->sometimes('password', new CustomerCheckPassword($params['email']), function ($input) {
// Check input to decide if rule should execute
});

Different method called when using Laravel form request validation

I have a controller (API\Fields) with a method named store, the route to that method is set up like this:
POST /api/templates/{template}/fields -> API\Fields#store
Everything worked properly until I created a very simple form request validation class with the following rules (This is the only thing I changed besides the return value for the authorize method):
return [
'name' => ['required', 'alpha_num'],
'coordinates' => ['required', 'json'],
'type' => ['required', BaseField::RULE],
'page' => ['required', 'numeric'],
'readonly' => ['sometimes', 'boolean'],
'required' => ['sometimes', 'boolean']
];
After I created the class, I simply changed the request class from Request, to CreateFieldsRequest and it messed pretty much the whole routing for that route up. Instead of calling store, Laravel seems to be calling index. When I restore CreateFieldsRequest back to just the Request class, it behaves as it should again.
I haven't been able to find any information on this topic, and I've verified over and over that I don't have some sort of incorrect routing or redirections on any of the related classes.
Any help or guidance with this would be greatly appreciated, thank you!
When I run the request through the Chrome developer console as a POST request, Laravel kicks it back as a "GET" request, not sure why.
A FormRequest that fails validation issues a redirect. It's the default behavior.
If you issue an AJAX request, or request a JSON response with an Accept header, it'll respond with a JSON list of validation errors and a 422 HTTP code instead.
After running a very simple test I realized that this seems to be an issue with Postman. If you are experiencing this issue stick to adding a _method=POST parameter on your POST body, or simply use XHR or a different API testing tool.
Edit: After further testing I realized the issue had not been fixed. When I run the request through the Chrome developer console as a POST request, Laravel kicks it back as a "GET" request, not sure why.

Laravel: How do I validate a date ONLY if the date exists?

I have a form, it has a date field called starts, which is optional:
...
<input type="date" name="starts">
...
Then I created a Request in Laravel that checks, among other things, if starts is a date, so the rules() function in the Request is somthing like:
public function rules()
{
return [
... (more validation rules)
'starts' => 'date',
... (more validation rules)
];
}
So, when I submit the form and there's no starts, the validation rules kicks in, it says it's not a date, and returns to my form.
How do I tell Laravel that starts is a date, only if it is present?
I'm looking something like the validation in files, which only take place if there's a file present
You can add "nullable" for your laravel validation rule like so:
'starts' => 'date|nullable'
Try 'starts' => 'nullable|date' as validation rule. There is a section about this in the documentation.

Laravel api route validation not validating

I did move from Lumen to Laravel and now converting my project over. Everything is working except the validation. For some reason, if I try to validate, it just redirects to the welcome.blade.php view. What could cause this?
I am using only the API part of routes, not the view. I am not dealing with views. I am using the stateless part of Laravel.
According to documentation, I can validate like this:
$this->validate($request, [
'title' => 'required|unique|max:255',
'body' => 'required',
]);
If validation passes, your code will keep executing normally. However,
if validation fails, an
Illuminate\Contracts\Validation\ValidationException will be thrown.
I also tried to force it to return JSON response without success:
$validator = $this->validate($request, ['email' => 'required']);
if ($validator->fails()) {
$messages = $validator->errors();
return new JsonResponse(['status' => 'error', 'messages' => $messages]);
}
However, mine doesn't fail but just returns the welcome view with response code of 200. I have tried pretty much all the possible validation methods from the documentation and from google. Non of them are working.
I even tried with clean laravel install, declared one test route and test controller which had the validation and the result is the exact same.
Is the validation even meant to be compatible with the restful/stateless part of Laravel?
Any suggestion is much appreciated.
1- first the unique key needs a table, per example if you want the email to be unique in the users table you do as follows:
'email' => 'required|unique:users',
I think may be you have placed your route in route/web.php file. Replace that code from web.php to api.php
Try to place your API endpoints in route/api.php file.
And remember you need to add prefix /api in your route.
Ex : test.com/api/users.

Laravel: Apply validation rule only if the another one passed

In my Laravel 5.2 app, I have the following validation rules to check a field:
$rules = array(
'file' => 'mimes:jpg,png,pdf,doc,docx',
'file' => 'validate_file'
);
Now, the validate_file is a custom validation rule. I want to run it only only if the first mimes validation passes.
I know I could simply validate/redirect with errors - in two batches, first the mimes, then the validate_file, but it seems like an overkill.
Any way I can do it the smart way in Laravel 5.2?
Use "bail" attribute. It will stop validation after first failure.
$this->validate($request, [
'title' => 'bail|mimes:jpg,png,pdf,doc,docx|validate_file',
]);
https://laravel.com/docs/5.2/validation#validation-quickstart search for "bail"

Categories