2016-02-11 131 views
2

我正在使用dropzone.js上傳文件。在我的控制方法,我有以下的驗證設置:Dropzone.js並在Laravel 5.1中顯示請求驗證錯誤

$this->validate($request, ['logo' => 'image|mimes:jpg,jpeg,gif']); 

如果驗證失敗,則拋出與驗證錯誤的JSON

{"logo":["The logo must be an image.","The logo must be a file of type: jpg, jpeg, gif."]} 

隨着dropzone.js我怎麼能解析422服務器響應錯誤和插入以下<p>標籤:

@if ($errors->has('logo')) <p class="help-block" id="logo-error">{{ $errors->first('logo') }}</p> @endif 

我有我的懸浮窗腳本的錯誤事件聲明,但似乎沒有當我做一個控制檯出現.log:

var baseUrl = "{{ url('/') }}"; 
Dropzone.autoDiscover = false; 

$("#my-dropzone").dropzone({ 
    url: baseUrl + "/upload", 
    paramName: "logo", 
    uploadMultiple: false, 
    maxFiles: 1, 
    dictDefaultMessage: '', 
    init: function() { 
    this.on("addedfile", function(file) { 
     console.log('addedfile...'); 
     if (this.files[1]!=null){ 
     this.removeFile(this.files[0]); 
     } 
    }); 
    this.on("thumbnail", function(file, dataUrl) { 
     console.log('thumbnail...'); 
     $('.dz-image-preview').hide(); 
     $('.dz-file-preview').hide(); 
    }); 
    this.on("sending", function(file, xhr, formData) { 
     formData.append("_token", $('meta[name="csrf-token"]').attr('content')); 
    }); 
    this.on("success", function(file, res) { 
     console.log('upload success...'); 
     $('#img-thumb').attr('src', res.path); 
     $('input[name="logo"]').val(res.path); 
    }); 

    }, 
    error: function(file, response) { 
    console.log(response); 
    } 
}); 

回答

0

您需要在這裏使用jQuery。由於您正在使用Laravel驗證,它將返回錯誤狀態。所以我們可以在你正在製作的AJAX請求的錯誤事件中編寫任何需要的內容,即。這裏的dropzone初始化。一個示例代碼就會像下面,

success: function(file, response) { 
     $('.profile-image-wrapper').removeClass('has-error'); 
     $('.profile-image-error').html(''); 
    }, 
    error: function(file, response) { 
     var $message = response.errors.profilePhoto; 
     $('.profile-image-wrapper').addClass('has-error'); 
     $('.profile-image-error').html('<strong>' + $message + '</strong'); 
    }, 

的「PARAMNAME」屬性爲我的懸浮窗初始化「profilePhoto」。所以錯誤也會以相同的順序提供。