skip to Main Content

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


  1. The problem is due to the order of your validation rules. The mimes and max rules are still being checked even when customLogo is not required. Instead, you can use the sometimes validation rule, which only applies to other rules if the field is present in the input array.

    protected $rules = [
        'domain' => ['required','regex:/([A-z]|d+|-|.)+(.com|.co.id)$/'],
        'logo' => ['required'],
        'customLogo' => ['sometimes', 'required_if:logo,custom', 'max:4096', 'mimes:png,svg'],
    ];
    
    Login or Signup to reply.
  2. You should use the nullable rule to indicate that the customLogo field can also be null (or empty).

    By using the rule

    'customLogo' => 'required_if:logo,custom|nullable|max:4096|mimes:png,svg'
    

    When the customLogo is null or not sent but the value of logo is "custom", then the required validation will run. However, if the value of logo is other than "custom" and the customLogo is null, 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:

    public function prepareForValidation()
    {
        $customLogo = $this->post('logo') === 'custom' ? $this->input('customLogo') : null;
        $this->merge(['customLogo' => $customLogo]);
    }
    

    This will help to make sure that customLogo is always null even if the file was uploaded when using $request->validated() when the value of logo is not "custom"

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search