Search code examples
jquerylaravelfile-uploadlaravel-4laravel-validation

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


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.


Solution

  • 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]);
    }