3

I have used single validation rule only for file input field. That is mimes rule. I wanted to skip this rule if no file is uploaded, so i have not used 'required' rule. But it is always showing mime type message even if no file is uploaded. I have just added required rule for testing , at that time it shown required error message. This problem is only when submitting form using ajax with jquery.form.js

1
  • 1
    Add sometimes to your rule. Commented May 30, 2017 at 14:43

4 Answers 4

3

You can use the sometimes validation type for that.

'file' => 'sometimes|mimes:jpeg,png'

Validating When Present

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.

Official Laravel docs

Sign up to request clarification or add additional context in comments.

Comments

1

You can use sometimes rule.

'photo' => 'sometimes|mimes:jpeg,bmp,png'

You can check more about it here https://laravel.com/docs/5.4/validation#conditionally-adding-rules

1 Comment

Still not working in my form. I think the problem is when using ajax form submission using jquery.form js
1

I've issued the same problem recently with ajax uploading, and handled the file validation using

public function rules()
{
    $rules = [
        'invitation_message' => 'required'
    ];

    if (request()->hasFile('invitation_excel_sheet')) {
        $rules = array_merge($rules, [
            'invitation_excel_sheet' => 'mimes:xlsx,csv'
        ]);
    }

    return $rules;
}

Comments

0

Another way is to use exclude_if in model:

public function rules()
{
    return [
        'link' => 'sometimes',
        'newPdf' => 'exclude_if:link,null|mimes:pdf',
    ];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.