Laravel validation rules - how optional, but only if another condition is true - laravel

How can I make a custom rule using Validation, so that the field can be nullable 'since' call function the result is true, otherwise, the field becomes required.
Of course I tried to use the 'nullable', but even if the field is empty, the Validation should execute the checkAreasDiff() function to validate that the field can be empty during the update.
In my controller, I created a function:
private function validator_update(array $data) {
\Validator::extend('areas_diff', function($attribute, $value, $parameters, $validator) {
return checkAreasDiff();
}, 'VALIDATOR AREAS_DIFF OK.');
/**
* RULES
*/
$rules = [
'fiscalizoarea' => 'areas_diff',
];
/**
* Return \Validator
*/
return \Validator::make($data, $rules, $msgs);
}

If I understand the question correctly, you want one field to be required only if another is not null?
There is a Laravel rule for that already: required_with.
required_with:foo,bar,...
The field under validation must be present and not empty only if any
of the other specified fields are present.
Or, if I'm getting your logic back to front: required_without
required_without:foo,bar,...
The field under validation must be present and not empty only when any
of the other specified fields are not present.

Related

Laravel 5.3 set second attribute name in custom validation rule

I have the following custom validation rule...
Validator::extend('empty_with', function ($attribute, $value, $parameters, $validator) {
$other = array_get($validator->getData(), $parameters[0], null);
return ($value != '' && $other != '') ? false : true;
}, "The :attribute field is not required with the :other field.");
And am using it like...
$validator = Validator::make($request->all(), [
'officer' => 'sometimes|integer',
'station' => 'empty_with:officer,|integer',
]);
The current error message am getting is
The station field is not required with the:otherfield.
Versus what I would like to have;
The station field is not required with the officer field.
How do I set a the second parameter 'officer' in the error message, the same way :attribute is...??
You'll need to add in a custom replacer to go with your custom validation rule. See 'Defining the error message' here.
\Validator::replacer('empty_with', function ($message, $attribute, $rule, $parameters) {
return str_replace(':other', $parameters[0], $message);
});
This code tells Laravel that when the empty_with rule fails, the message should be run through that closure before being passed back to the user. The closure performs a simple string replacement and returns the amended error message.
For the most part, each validation rule has its own replacement rules for messages since it's dependent on the specific attributes and their order. Although :other being replaced with the first parameter happens for a few rules, it's not automatic and is defined explicitly for each rule that uses it. It's worth looking in the Illuminate\Validation\Concerns\ReplacesAttributes trait to get an idea of how Laravel deals with replacement for its built-in rules.

Laravel custom validation: only validate input if input given

So I followed this tutorial to learn how to upload images with Laravel using Vue: Image upload and validation using Laravel and VueJs
Everything works fine, but I want to make the image upload optional. Now the custom validation fails for the AppServiceProvider. if it does not have any input then i get this error
trying to access an attribute inside an array that does not exist. Undefined offset: 1
I could avoid the error by asking
if (request('image'))
In the controller and applying the validation for the other fields only if no image is given. However, this gets incredibly messy.
So I am looking for a way to get the custom validation rule working if there is no input. Or is that the wrong way?
Here is the custom validation rule:
public function boot()
{
Validator::extend('image64', function ($attribute, $value, $parameters, $validator) {
$type = explode('/', explode(':', substr($value, 0, strpos($value, ';')))[1])[1];
if (in_array($type, $parameters)) {
return true;
}
return false;
});
Validator::replacer('image64', function($message, $attribute, $rule, $parameters) {
return str_replace(':values',join(",",$parameters),$message);
});
}
In some situations, you may wish to run validation checks against a field only if that field is present in the input array. To quickly accomplish this, add the sometimes rule to your rule list:
$v = Validator::make($data, [
'email' => 'sometimes|required|email',
]);
In the example above, the email field will only be validated if it is present in the $data array.
Reference: Conditionally Adding Rules
Laravel provides a validation called 'nullable' in case other validation rules should not be run if the given value is null: A Note On Optional Fields

Laravel validation rule "URL" does not pass empty value

I have input text field whith validation rule :
public function rules()
{
return [
'field' => 'url',
];
}
It`s not required (field can be empty) but validation return an error.
Solve problem use "nullable":
public function rules()
{
return [
'field' => 'nullable|url',
];
}
Add sometimes rule to the validation. This means to validate it for a URL when the value is not given or null.
public function rules()
{
return [
'field' => 'sometimes|url',
];
}
when we submmitting values from js, like through a FormData, the value null could be submitted as string containing 'null', which may pass a nullable rule, cause further type check fail. so be sure to make this value be posted as '', literaly nothing, no a 'null' string
When you use formData (js) to submit your request, "null" is assigned by default for all empty fields. This will pass through Laravel "nullable" validaton and indicate as invalid input. So, please, use something like below in your validation rules.
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
$rules = [];
if($this->filled('field') && $this->field!= 'null'){
$rules['field'] = 'url';
}
return $rules;
}
In order to do this use laravel's form requests. https://laravel.com/docs/8.x/validation#creating-form-requests

create a custom validation in laravel where input value must be greater than the existing value in the database

I have a Printer model which has a page_count field..
the user will be able to input the current page_count...
the new page_count must be greater than the existing data in the database... How can I do that?
I had the same issue solved like this, though someone already gave the solution in the comments section.
/**
* #param array $data
* validates and Stores the application data
*
*/
public function sendMoney(Request $request)
{
//get the value to be validated against
$balance = Auth::user()->balance;
$validator = Validator::make($request->all(), [
'send_to_address' => 'required',
'amount_to_send' => 'required|max:'.$balance.'|min:0.01|numeric',
]);
//some logic goes here
}
Depending on your use case you could modify...
Happy Coding
Assuming you have Printer model which contains the page_count column.
You can define a custom validation rule in your AppServiceProvider's boot() method.
public function boot()
{
//your other code
Validator::extend('page_count', function($attribute, $value, $parameters, $validator) {
$page_count = Printer::find(1)->first()->value('page_count'); //replace this with your method of getting page count.
//If it depends on any extra parameter you can pass it as a parameter in the validation rule and extract it here using $parameter variable.
return $value >= $page_count;
});
//your other code
}
Then, you can use it in your validation rule like below
'page_count' => 'required|page_count'
Reference: Laravel Custom Validation

Validate only if the field is entered in Laravel 5.2

public function rules() {
return [
'num_of_devices' => 'integer'
];
}
I want to validate an integer field if and only if the field is entered. But above rule validates it for integer even if the field is empty. I used somtimes, but no result. But when I var_dump($num_of_devices) it is string.I am using Laravel 5.2. I think It was working fine in 5.1.
From version 5.3 you can use nullable
public function rules() {
return [
'num_of_devices' => 'nullable | integer'
];
}
Add a rule to array, if input is not empty. You could collect all your validation rules to $rules array and then return the array.
if( !empty(Input::get('num_of_devices')) ){
$rules['num_of_devices'] = 'integer';
}
You’re looking for the sometimes validation rule. From the documentation:
…run validation checks against a field only if that field is present in the input array.

Resources