Laravel file validation after submitting form via jquery submit();

1.6k Views Asked by At

When i try to validate a image file after submitting the form via jquery

$('#logo').submit(); 

am always getting the validation error as

The img field is required

Here is the validation that i used for validating the file

$input = array('img' => Input::file('img'));
$rules = array(
        'img' => 'required',
);
// Now pass the input and rules into the validator
$validator = Validator::make($input, $rules);

// check if the validator failed -----------------------
if ($validator->fails()) {
    // get the error messages from the validator
    $messages = $validator->messages();
    // redirect our user back to the form with the errors from the validator
    print_r($messages);
}

I failed to identify what is the problem with the script, Help me to overcome the issue. Thanks in advance.

2

There are 2 best solutions below

1
On BEST ANSWER

To submit files with jQuery + ajax to Laravel, I follow this approach:

An example form:

<form class="form-horizontal" role="form" method="POST" id="imageUpload" action="some/backend/method" enctype="multipart/form-data">
    <div class="form-group">
        <div class="alert alert-danger" style="display: none;"></div>
        <label class="col-sm-3 control-label no-padding-right"> <i class="fa fa-asterisk light-red"></i> Image</label>
        <div class="col-sm-9">
            <input type="file" name="image" class="form-control" required/>
        </div>
    </div>
</form>

Note: set an ID to the form.

An example ajax request:

$.ajax({
    type: 'POST',
    data: new FormData($("#imageUpload")[0]),
    url: 'some/backend/method',
    processData: false,
    contentType: false
}).done(function (result) {
    if ($.isEmptyObject(result.error)) {
        window.location.reload();
    } else {
        var messages = '';
        for (var key in result.error) {
            if (result.error.hasOwnProperty(key)) {
                messages += result.error[key] + '<br />';
            }
        }
        $("#imageUpload .alert").html(messages).css('display', 'block');
    }
}, "json");

Note: processData: false & contentType: false are quite important.

And in the backend (Laravel):

$validator = Validator::make(Input::all(), [
    'image' =>'required'
]);

if ($validator->fails()) {
    return Response::json(['error' => $validator->messages()]);
} else {
    return Response::json(['success' => true]);
}
0
On

If you are submitting a form that has <input type="file"> with ajax/jquery, It is almost impossible, Unless you use something like Jquery file upload or dropzone.js, etc. But then You still have an alternative to do it by yourself, using XMLHttpRequest. An example below:

var forms = document.querySelector('form#yourFormId');

   var request = new XMLHttpRequest();

   var formDatas = new FormData(forms);
   request.open('post','upload');
   //Here "upload" is your post route
   request.send(formDatas);

   request.onreadystatechange = function() {
    if (request.readyState === 4) {
      if (request.status === 200) {
       //The request was successful

     }else{

    //Request wasn't OK
}

Then you should be able to just call you input file name in your Controller:

Input::get('inputFileName')