I am currently validating a form with this rule validation
protected $rules = [
'domain' => ['required','regex:/([A-z]|d+|-)+(.com)$/'],
'domain' => ['required','regex:/([A-z]|d+|-|.)+(.com|.co.id)$/'],
'logo' => ['required'],
'customLogo' => 'required_if:logo,custom|max:4096|mimes:png,svg',
];
I have set that it is required if logo value ‘custom’ and it was null but it is still validating the mimes which cause error.
I am using Livewire form validation with this method
$input = $this->validate();
I really appreciate any answer
2
Answers
The problem is due to the order of your validation rules. The
mimes
andmax
rules are still being checked even whencustomLogo
is not required. Instead, you can use thesometimes
validation rule, which only applies to other rules if the field is present in the input array.You should use the
nullable
rule to indicate that the customLogo field can also be null (or empty).By using the rule
When the
customLogo
isnull
or not sent but the value oflogo
is "custom", then therequired
validation will run. However, if the value oflogo
is other than "custom" and thecustomLogo
isnull
, the validation will pass.Also, it would be better if you are using the
prepareForValidation
method for this type of case of FormRequest as it will help to filter out the data and get properly formatted data in the controller.Something like:
This will help to make sure that
customLogo
is always null even if the file was uploaded when using$request->validated()
when the value oflogo
is not "custom"