Create rule to make request only contain certain keys - php

I am using the Lumen Framework, which utilizes the Laravel Validation
I wanted to create a Validator Rule to make the Request->input() json only contain specific keys at the root like "domain" and "nameservers". Not more and not less.
Example passing the rule:
{
"domain":"domain.tld",
"nameservers":
{...}
}
Example not passing the rule:
{
"domain":"domain.tld",
"nameservers":
{...},
"Hack":"executeSomething()"
}
I tried to use to use several default validation rules to achieve this but wasnt successful.
My approach was now to put the request in another array like this
$checkInput['input'] = $request->all();
to make the validator validate the "root" keys.
Now this is my Approach:
create the validator
$checkInput['input'] = $request->all();
$validator = Validator::make($checkInput, [
'input' => [
'onlyContains:domain,nameservers'
],
]);
creating the rule
Validator::extend('onlyContains', function($attribute, $value, $parameters, $validator){
$input = $validator->getData();
$ok = 0;
foreach ($parameters as $key => $value) {
if (Arr::has($input, $attribute . '.' . $value)) {
$ok++;
}
}
if (sizeof(Arr::get($input, $attribute)) - $ok > 0) {
return false;
}
return true;
});
It seems i got the desired result, but i am asking if there is maybe smarter solution to this with the default rules provided by Laravel/Lumen.

You are trying to do a blacklisting approach blocking out fields that are not intended. A simple approach, that is utilized a lot, is to only fetch out the validated. Also you are trying to do logic, that goes against normal validation logic, to do it a field at a time.
This is also a good time, to learn about FormRequest and how you can get that logic, into a place where it makes more sense.
public function route(MyRequest $request) {
$input = $request->validated();
}
With this approach, you will only ever have the validated fields in the $input variable. As an extra bonus, this approach will make your code way easier to pick up by other Laravel developers. Example form request below.
public class MyRequest extends FormRequest
{
public function rules()
{
return [
'domain' => ['required', 'string'],
'nameservers' => ['required', 'array'],
];
}
}

You should use prohibited rule.
For eg:
$allowedKeys = ['domain', 'nameservers'];
$inputData = $request->all();
$inputKeys = array_keys($inputData);
$diffKeys = array_diff($inputKeys, $allowedKeys);
$rules = [];
foreach($diffKeys as $value) {
$rules[$value] = ['prohibited'];
}

Related

How to avoid duplication in Laravel validation rules

For validating form validation rules I currently stored them in User Model and use it in Register Controller, User controller in admin panel, User Controller in APIs and some other places, but currently it's very hard to maintain because each controller needs a slightly different set of rules and when I change the rules in User Model other controllers will not work anymore. So how to avoid duplication in rules and still keep the code maintainable?
Approach I often use is to write a HasRules trait for my models, it looks something like this:
trait HasRules
{
public static function getValidationRules(): array
{
if (! property_exists(static::class, 'rules')) {
return [];
}
if (func_num_args() === 0) {
return static::$rules;
}
if (func_num_args() === 1 && is_string(func_get_arg(0))) {
return array_get(static::$rules, func_get_arg(0), []);
}
$attributes = func_num_args() === 1 && is_array(func_get_arg(0))
? func_get_arg(0)
: func_get_args();
return array_only(static::$rules, $attributes);
}
}
Looks messy, but what it does is allows you to retrieve your rules (from a static field if such exists) in a variety of ways. So in your model you can:
class User extends Model
{
use HasRules;
public static $rules = [
'name' => ['required'],
'age' => ['min:16']
];
...
}
Then in your validation (for example, in your FormRequest's rules() method or in your controllers when preparing rules array) you can call this getValidationRules() in variety of ways:
$allRules = User::getValidationRules(); // if called with no parameters all rules will be returned.
$onlySomeRules = [
'controller_specific_field' => ['required'],
'name' => User::getValidationRules('name'); // if called with one string parameter only rules for that attribute will be returned.
];
$multipleSomeRules = User::getValidationRules('name', 'age'); // will return array of rules for specified attributes.
// You can also call it with array as first parameter:
$multipleSomeRules2 = User::getValidationRules(['name', 'age']);
Don't be afraid to write some code for generating your custom controller specific rules. Use array_merge and other helpers, implement your own (for example, a helper that adds 'required' value to array if it's not there or removes it etc). I strongly encourage you to use FormRequest classes to encapsulate that logic though.
You can try using laravel's validation laravel documentation
it is really easy to use and maintain just follow these steps:
run artisan command: php artisan make:request StoreYourModelName
which will create a file in App/Http/Requests
in the authorize function set it to:
public function authorize()
{
return true;
}
then write your validation logic in the rules function:
public function rules()
{
return [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
];
}
Custom error messages add this below your rules function:
public function messages()
{
return [
'title.required' => 'A title is required',
'body.required' => 'A message is required',
];
}
Lastly to use this in your controller just add it as a parameter in your function.
public function create(Request $request, StoreYourModelName $storeYourModelName)
{
//
}
and that's all you need to do this will validate on form submission if validation passes it will go to your controller, keep in mind your validation logic does not have to be like mine thought i would show you one way that it can be done..

Laravel validation - comma separated string input as array

How can I validate one input with multiple values? I'm using bootstrap tagsinput plugin. It returns all tags in one field. I need to validate this tags - unique.
First I'm trying to place this tags into array and then validate it in request but still no luck.
Here is my code in request:
public function all()
{
$postData = parent::all();
// checkbox status
if(array_key_exists('keywords', $postData)) {
// put keywords into array
$keywords = explode(',', $postData['keywords']);
$test = [];
$i = 0;
foreach($keywords as $keyword)
{
$test[$i] = $keyword;
$i++;
}
$postData['keywords'] = $test;
}
return $postData;
}
public function rules()
{
$rules = [
'title' => 'required|min:3|unique:subdomain_categories,title|unique:subdomain_keywords,keyword',
'description' => '',
'image' => 'required|image',
'keywords.*' => 'min:3'
];
return $rules;
}
But as soon as keyword becomes invalid I get this error:
ErrorException in helpers.php line 531:
htmlentities() expects parameter 1 to be string, array given.
Any ideas what's wrong?
I was running into a similar problem with comma separated emails on 5.4. Here's how I solved it:
In your request class, override the prepareForValidation() method (which does nothing by default, btw), and explode your comma separated string.
/**
* #inheritDoc
*/
protected function prepareForValidation()
{
$this->replace(['keywords' => explode(',', $this->keywords)]);
}
Now you can just use Laravel's normal array validation!
Since my case needed to be a bit more explicit on the messages, too, I added in some attribute and message customizations as well. I made a gist, if that's of interest to you as well
Instead of mutating your input, for Laravel 6+ there is a package to apply these validations to a comma separated string of values:
https://github.com/spatie/laravel-validation-rules#delimited
You need to install it:
composer require spatie/laravel-validation-rules
Then, you can use it as a rule (using a FormRequest is recommended).
For example, to validate all items are emails, not long of 20 characters and there are at least 3 of them, you can use:
use Spatie\ValidationRules\Rules\Delimited;
// ...
public function rules()
{
return [
'emails' => [(new Delimited('email|max:20'))->min(3)],
];
}
The constructor of the validator accepts a validation rule string, a validation instance, or an array. That rules are used to validate all separate values; in this case, 'email|max:20'.
It's not a good practice to override the all() method to validate a field.
If you receive a comma separated String and not an array that you want to validate, but there is no common Method available, write your own.
in your App/Providers/ValidatorServiceProvider just add a new Validation:
public function boot()
{
Validator::extend('keywords', function ($attribute, $value, $parameters, $validator)
{
// put keywords into array
$keywords = explode(',', $value);
foreach($keywords as $keyword)
{
// do validation logic
if(strlen($keyword) < 3)
{
return false;
}
}
return true;
}
}
Now you can use this Validation Rule on any request if needed, it is reusable.
public function rules()
{
$rules = [
'title' => 'required|min:3|unique:subdomain_categories,title|unique:subdomain_keywords,keyword',
'description' => 'nullable',
'image' => 'required|image',
'keywords' => 'keywords',
];
return $rules;
}
If the validation pass and you want to make the keywords be accessible in your request as array, write your own method:
public function keywords ()
{
return explode(',', $this->get('keywords'));
}

Add Custom Conditional Validation rules to the same attribute

I'm trying to add custom validation logic for file uploads for my admin panel. Right now my file fields can return either Illuminate\Http\UploadedFile or string|null if the file is not uploaded or changed or whatever. What I'm doing is, I created a custom rule that looks like this:
'image' => [
'required',
'admin_file:mimes:jpeg;png,dimensions:min_width=800;min_height=600'
]
I then parse all the arguments I pass, and the thing is, I naturally want all of them applied only if my value is an instance of UploadedFile. I use the following code for my custom validation:
<?php
class AdminFileValidator
{
public function validate($attribute, $value, $parameters, Validator $validator)
{
$rules = implode(
"|",
array_map(function($item) {
return str_replace(";", ",", $item);
}, $parameters)
);
$validator->sometimes($attribute, $rules, function() use ($value) {
return $value instanceof UploadedFile;
});
return true;
}
}
The problem is with adding additional rules to an attribute via sometimes doesn't work that way. The added rules are not being processed by a validator.
Is there any way to validate these rules without revalidating the whole thing manually?
What I see is that your are using sometimes inside of a rule. From my perspective you need to take it out, even better without use a custom class.
Using Validator object:
$validator = Validator::make($data, [
'image' => 'required',
]);
$validator->sometimes('image', 'mimes:jpeg;png,dimensions:min_width=800', function($value) {
return $value instanceof UploadedFile;
});
If you are using a Request class you could override the function getValidatorInstance in order apply the conditional rules:
protected function getValidatorInstance(){
$validator = parent::getValidatorInstance();
$validator->sometimes('image', 'mimes:jpeg;png,dimensions:min_width=800', function($value) {
return $value instanceof UploadedFile;
});
return $validator;
}

Lumen provide a code for validation errors

Currently in lumen when you use the $this->validate($request, $rules) function inside of a controller it will throw a ValidationException with error for your validation rules(if any fail of course).
However, I need to have a code for every validation rule. We can set custom messages for rules, but I need to add a unique code.
I know there's a "formatErrorsUsing" function, where you can pass a formatter. But the data returned by the passed argument to it, has already dropped the names of the rules that failed, and replaced them with their messages. I of course don't want to string check the message to determine the code that should go there.
I considered setting the message of all rules to be "CODE|This is the message" and parsing out the code, but this feels like a very hacked solution. There has to be a cleaner way right?
I've solved this for now with the following solution:
private function ruleToCode($rule) {
$map = [
'Required' => 1001,
];
if(isset($map[$rule])) {
return $map[$rule];
}
return $rule;
}
public function formatValidationErrors(Validator $validator) {
$errors = [];
foreach($validator->failed() as $field => $failed) {
foreach($failed as $rule => $params) {
$errors[] = [
'code' => $this->ruleToCode($rule),
'field' => $field,
];
}
}
return $errors;
}

Error when trying to extend validator in Laravel

I have been using the following validation for my form in Laravel:
public function isValid($data, $rules)
{
$validation = Validator::make($data, $rules);
if($validation->passes()){
return true;
}
$this->messages = $validation->messages();
return false;
}
The rules passed to it are simple:
$rules = [
'name' => 'required',
'type' => 'required'
];
And $data is the input post data. Now I need to add a custom validation extension to this, specifically to make sure that the value of input field round2 is greater than the value of input field round1. Looking at the docs, I have tried the following syntax which I think should be correct, but I keep getting an error.
$validation->extend('manual_capture', function($attribute, $value, $parameters)
{
return $value > $parameters[0];
});
Then I could call this with $attribute = 'round1', $value = $data['round1'] and $parameters = [$data['round2']].
The error is Method [extend] does not exist. - I'm not sure if my understanding of this whole concept is correct, so can someone tell me how to make it work? The docs only have about 2 paragraphs about this.
Put the following in your route.php
Validator::extend('manual_capture', function($attribute, $value, $parameters)
{
return $value > $parameters[0];
});
Additional documentation here
Then use it like so:
$rules = [ 'foo' => 'manual_capture:30'];

Categories