Laravel custom validation: only validate input if input given - laravel

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

Related

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

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.

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: Deny empty PUT requests in validation

Laravel 5.3's $api->resource() routes map PUT requests to the controller's update method.
I fail to trigger a validation error when an empty HTTP PUT request is made. My $this->validate() rules are all optional, since no field is required in an update.
But I'd really like to let validation fail if the request is empty (count($request->all() == 0).
Is there a way to do that with the in-built validation rules?
A validation rule of '*' => 'min:1' does not work.
I did not find a working in-built rule, so I registered a custom rule:
\Illuminate\Support\Facades\Validator::extendImplicit(
'requestnotempty',
function($attribute, $value, $parameters, $validator) {
return count($validator->getData()) !== 0;
}
);
Then I used it:
$this->validate(
$request,
[
'' => 'requestnotempty',
//...
]
);

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

Check if field exists in Input during validation using Laravel

I want to make sure that certain fields are posted as part of the form but I don;t mind if some are empty values.
The 'required' validation rule won't work as I am happy to accept empty strings. I have tried the below, but as the 'address2' field is never sent, the validator doesn't process it.
Any ideas?
$rules = array(
'address2' => 'attribute_exists'
);
class CustomValidator extends Illuminate\Validation\Validator {
public function validateAttributeExists($attribute, $value, $parameters)
{
return isset($this->data[$attribute]);
}
}
You can use Input::has('address2') to check if something is posted by address2 input name. See the example:
if(Input::has('address2')) {
// Do something!
}
In Laravel 5,
if($request->has('address2')){
// do stuff
}
You should make custom validator like this.
use Symfony\Component\Translation\TranslatorInterface;
class CustomValidator extends Illuminate\Validation\Validator {
public function __construct(TranslatorInterface $translator, $data, $rules, $messages = array())
{
parent::__construct($translator, $data, $rules, $messages);
$this->implicitRules[] = 'AttributeExists';
}
public function validateAttributeExists($attribute, $value, $parameters)
{
return isset($this->data[$attribute]);
}
}
This will make AttributeExists work without to use require. For more explain about this. When you want to create new validator rule. If you don't set it in $implicitRules, that method will not work out if you don't use require rule before it. You can find more info in laravel source code.
When you submit a form each and every field is posted, matter of fact is if you leave some filed empty then that field value is null or empty. Just check the POST parameters once, to do so open the firebug console in firefox and submit the form, then check the post parameters. As you want to accept empty string what is the use of any rule?
else You can do this
$addr2=Input::get('address2');
if(isset($addr2)){
//do here whatever you want
}else{
//do something else
$addr2='';//empty string
}
Actually, Laravel has a method to validate if an attribute exists even if not filled.
$rules = [
'something' => 'present'
];
All the validation rules are stored in Validator class (/vendor/laravel/framework/src/Illuminate/Validation/Validator.php), you can check for the implementation of each rule, even no documented rules.

Resources