qqmydarling
qqmydarling

Reputation: 177

Laravel File validation rule "Required" not working

So the title says all, other rules like "mimes" are works, but I can submit form without file upload. Ofcourse I can use "required" attr in HTML, but I don't want to.

Controller

$rules = [
    'img.*' => 'required|mimes:png,jpeg,jpg',
    ];

$customMessages = [
    'img.required' => 'Yo, what should I call you?',
    ];

$this->validate($request, $rules, $customMessages);

View

<div class="form-group{{ $errors->has('img.'.$i) ? ' has-error' : '' }}">

    <label for="img">File input</label>
    <input  type="file" class="form-control-file" id="img" value="{{old('img.'.$i)}}" name="img[]">
    <small class="text-danger">{{ $errors->first('img.'.$i) }}</small>

</div>

I have other inputs, but with type="text" and their "required" rule works fine. Whats wrong with type="file"? Can't find the answer...

Upvotes: 2

Views: 6934

Answers (4)

AddWeb Solution Pvt Ltd
AddWeb Solution Pvt Ltd

Reputation: 21691

You should try this:

<input  type="file" class="form-control-file" id="img" value="{{old('img.'.$i)}}" name="img[]" multiple>


$rules = [
        'img' => 'required',
        'img.*' => 'image|mimes:png,jpeg,jpg'
    ];

Upvotes: 2

qqmydarling
qqmydarling

Reputation: 177

So, the problem was in $iter in my div for input type="file" It should look like this:

 <div class="form-group{{ $errors->has('img') ? ' has-error' : '' }}">
      <label for="img">File input</label>
      <input type="file" class="form-control-file" id="img" value="{{old('img')}}" name="img[]">
      <small class="text-danger">{{ $errors->first('img') }}</small>
 </div>

But, after I delete my variable mimes stopped work:)

$rules = [
        'img' => 'required',
        'img.*' => 'image|mimes:png,jpeg,jpg'
    ];

or

$rules = [
        'img.*' => 'required|image|mimes:png,jpeg,jpg'
    ];

Upvotes: 0

Sreejith BS
Sreejith BS

Reputation: 1203

Controller

$rules = [
    'img' => 'required',
    'img.*' => 'image|mimes:png,jpeg,jpg',
];

$customMessages = [
    'img.required' => 'Yo, what should I call you?',
];

$this->validate($request, $rules, $customMessages);

form

<form action="...." method="post" enctype="multipart/form-data">
.
.
.
.

    <div class="form-group{{ $errors->has('img.'.$i) ? ' has-error' : '' }}">

        <label for="img">File input</label>
        <input  type="file" class="form-control-file" id="img" value="{{old('img.'.$i)}}" name="img[]">
        <small class="text-danger">{{ $errors->first('img.'.$i) }}</small>

    </div>

Upvotes: 0

user223321
user223321

Reputation: 153

In your opening form tag you have add this:

enctype="multipart/form-data"

and remove name="img[]" use name ="img"

Upvotes: 2

Related Questions