Laravel validation for accepting only predefined values from api - laravel

Basically I wrote an api in laravel, The api should return a validation error if any of the key has wrong values (spelling mistakes,extra space). To make more clarity, in the web interface these key values are from select boxes . so users do not get to type anything.
First consider using in_array function for every inputs. I think that works. But i would like to know if there is anything for laravel specific.
something like
'email' => 'required | email| 'sandy#stackoverflow.com'
to make it ease. I could not find it unfortunately. It seems not that hard.

I believe you can achieve this with in, for example:
$rule = [
'email' => 'in:sandy#stackoverflow.com',
];
Or you could try it including the Rule namespace as described in the docs here
use Illuminate\Validation\Rule;
Validator::make($data, [
'zones' => [
'required',
Rule::in(['first-zone', 'second-zone']),
],
]);

Related

Laravel validation - Different Attributes Specifications

I'm using a LaravelMiddleware, which should check for Access.
Therefore, I check for a specific Attributes, which sometimes have different names.
EG:
$request->key
$request->moduleKey
Im asking if there is a possiblitiy to check for 2 different attributes specifications?
Like so:
$data = $request->validate([
'key|moduleKey' => ['required', 'numeric'],
]);
It's not possible this way, but you have 2 other options:
Validation
https://laravel.com/docs/9.x/validation#rule-required-without
$data = $request->validate([
'key' => ['required_without:moduleKey', 'numeric'],
'moduleKey' => ['required_without:key', 'numeric'],
]);
but the problem is you still dont know which one you need unless you always get them both: $data['key'] ?? $data['moduleKey']
You can also update the request beforenhand:
$request['key'] = $request['key'] ?? $request['moduleKey'];
$data = $request->validate([rules]);
this code above you could put in a middleware to make sure every request always have the "key" variable in the request.

Laravel validation rules shared between Form request and Validator in command

I have a set of validation rules in a FormRequest, Laravel 6.X like so:
{
return [
'rule1' => 'required|numeric',
'rule2' => 'required|numeric',
...,
'ruleN.*.rule1' => ''required|string|max:50'
];
}
This works just fine for every AJAX HTTP request against the endpoint for it was created. However, I also need to run the same process (Validate this time not against a Request but an array of inputs) via a CLI command, where this FormRequest cannot be used, as it won't be a Request.
By trying to inject the FormRequest into a Command like:
public function handle(CustomFormRequest $validator)
{
...
}
the command execution always fails (Of course), on every run, as the type of input isn't a Request.
Googling a bit I ended up with a solution of the shape of (Rules will be the same ofc):
$validator = Validator::make([
'rule1' => $firstName,
'rule2' => $lastName,
], [
'rule1' => ['required'],
'rule2' => ['required'],
]);
However I'd like to share the set of rules in a common place (A file for example) and that both the FormRequest AND the Validator class can take the same rules, without writing in both places (Form Request and Command), to keep them the same under any changes.
Is there way of writing the "rules" array in a common place (A file for example) and import them into both places? Maybe a base class would work, but it doesn't look right to do it, as they don't share anything else than that. I thought of a Trait, but I'm hesitant tht could be the best solution.

Laravel validations

I want to validate my backend code with the following data.I passed date as $request->get('date_from'),$request->get('date_to') and time as $request->get('time_from'), $request->get('time_to') from my angular frontend and I convert date time as follows.
$dateTime_from=date('Y-m-d',strtotime($request->get('date_from'))).' '.$request->get('time_from');
$dateTime_to=date('Y-m-d',strtotime($request->get('date_to'))).' '.$request->get('time_to');
Now I want to validate DateTime with laravel backend validations. dateTime_from should be less than dateTime_to.How can write down that code inside validator?
$this->validate($request, [
'vehicle_id'=>'required',
'time_to'=>'required',
'event_id'=>'required',
]);
You can use the after validation rule.
$this->validate($request, [
'vehicle_id' => 'required',
'date_to' => 'required|after:date_from',
'event_id' => 'required'
]);
https://laravel.com/docs/5.8/validation#rule-after
you can use the after rule like follows
'date_to' => 'required|date|after:date_from'
Instead of passing a date string to be evaluated by strtotime, you may specify another field to compare against the date:
Also, you have rule-before as well
EDIT
I think after rule takes the time into consideration as well, but not sure.
And you have really complex validation to do, better write a custom rule class or a closure to handle it for you
'date_to' => [ 'required',
'date',
function ($attribute, $value, $fail) {
if (strtotime($value) <= strtotime($request->date_from) {
$fail(':attribute needs to be higher than date_from!'); // or whatever mesage ou need to send
}
]

Laravel Active Validation Rule

I am extremely new to Laravel and I was wondering if you could help me create a Custom Validation Rule, I am using version 5.5 of Laravel.
What I try to do is the following, I understand that the validations can be defined in the following way:
'email' => 'required|string'
I would like to add a new rule, in specific one called 'active'
In the application that I want to create I have several tables in which there are columns called 'active' (boolean) .. example
Users:
id|name|email|active
Roles:
id|name|active
I need a rule that I can call as follows:
'email' => 'required|string|active'
In short, I need a rule that verifies in a specific table, if the value I'm validating is active, and if not, send me a message. Thank you very much in advance
Try to use the Rule class and 'exists' validation:
use Illuminate\Validation\Rule;
'email' => [
'required',
'string',
Rule::exists('your_table')->where(function ($query) {
$query->where('active', 1);
}),
]

Validating Matching Strings

When I use the Validation feature in Laravel, how can I add a pre-defined strings that are allowed in an Input?
For example, let's say I want the Input to contain only one of the following: foo,bar,baz, how can I do that?
$validator = Validator::make($credentials, [
'profile' => 'required|max:255', // Here I want Predefined allowed values for it
]);
Best to use the 'in' validation rule like this:
$validator = Validator::make($credentials, [
'profile' => ["required" , "max:255", "in:foo,bar,baz"]
]);
It is recommended in Laravel docs to put the validation rules in an array when they get bigger and I thought 3 rules were sufficient. I think it makes it for a more readable content but you do not have to. I added the regex portion below and I have it works. I am not that great with regexing stuff. Let me know.
$validator = Validator::make($credentials, [
'profile' => ["required" , "max:255", "regex:(foo|bar|baz)"]
]);
Works for me in Laravel 9:
use Illuminate\Validation\Rule;
 
Validator::make($data, [
'toppings' => [
'required',
Rule::notIn(['sprinkles', 'cherries']),
],
]);
Docs: https://laravel.com/docs/9.x/validation#rule-not-in
For the opposite you could use Rule::in(['foo', 'bar', 'baz'])

Resources