gpt4 book ai didi

jquery - 通过 jquery Submit() 提交表单后 Laravel 文件验证;

转载 作者:行者123 更新时间:2023-12-01 04:45:25 24 4
gpt4 key购买 nike

当我通过 jquery 提交表单后尝试验证图像文件时

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

我总是收到验证错误

The img field is required

这是我用于验证文件的验证

$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);
}

我无法确定脚本的问题是什么,帮助我克服这个问题。提前致谢。

最佳答案

要使用 jQuery + ajax 向 Laravel 提交文件,我遵循以下方法:

示例表单:

<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.

ajax 请求示例:

$.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.

在后端(Laravel):

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

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

关于jquery - 通过 jquery Submit() 提交表单后 Laravel 文件验证;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30659757/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com