I have required file field which is recorded in the database as a path. I want to make it optionally required if its field in the database is null. In the update
action of my controller I have set the following validation:
$this->validate(request(),[
'drawings' => 'requiredIfEmpty:'.$product->drawings.'|file|max:'. config('fox.photoMaxSize').'|mimes:pdf',
Then in app/Providers/AppServiceProvider.php
I defined requiredIfEmpty
validator:
Validator::extend('requiredIfEmpty',function ($attribute,$value,$parameters,$validator){
if(is_null($parameters[0]) || empty($parameters[0])){
if (is_null($value)){
return false;
}
}
return true;
});
Validator::replacer('requiredIfEmpty', function ($message, $attribute, $rule, $parameters) {
return __('The :attr is required',['attr' => $attribute]);
});
In the view _form
I use laravel-collective form helper like the following for the drawings
field:
<div class="form-group ">
@if (!is_null($product->drawings))
<a href="" target="_bfox"><img src="/imgs/pdf.png" alt="" title="" /></a>
<br>
@else
<img src="/imgs/empty.png" width="64" height="64" alt="..." title="..." /> <br>
@endif
{!! Form::label('drawings', __('Drawings')) !!}
{!! Form::file('drawings',['class' => 'btn btn-info','title' =>__('PDF file')]); !!}
@php ($eleE = $errors->first('drawings'))
@include('layouts.form-ele-error')
</div>
The problem is, my custom validation rule does not invoked because the field is not required and it has null value. I need any way that allows the two scenarios:
- when the
drawings
file field is empty and$product->drawings
is not null, there's no validation occured - when the
drawings
file field is empty and$product->drawings
is null, the validation occurred.
In other words, I need a built in validation rule like requiredIf
but it does not take another form field as parameter, it just take another value and it always works even the form field value is empty and the field is not required.
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire