laravel 如何在laravel中使用ajax验证输入数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49333789/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to validate input data using ajax in laravel
提问by RajB009
testAjax functioninsidePostsController class:
testAjax函数里面PostsController类:
public function testAjax(Request $request)
{
$name = $request->input('name');
$validator = Validator::make($request->all(), ['name' => 'required']);
if ($validator->fails()){
$errors = $validator->errors();
echo $errors;
}
else{
echo "welcome ". $name;
}
}
inside web.phpfile:
在web.php文件中:
Route::get('/home' , function(){
return view('ajaxForm');
});
Route::post('/verifydata', 'PostsController@testAjax');
ajaxForm.blade.php:
ajaxForm.blade.php:
<script src="{{ asset('public/js/jquery.js') }}"></script>
<input type="hidden" id="token" value="{{ csrf_token() }}">
Name<input type="text" name="name" id="name">
<input type="button" id="submit" class="btn btn-info" value="Submit" />
<script>
$(document).ready(function(){
$("#submit").click(function(){
var name = $("#name").val();
var token = $("#token").val();
/**Ajax code**/
$.ajax({
type: "post",
url:"{{URL::to('/verifydata')}}",
data:{name:name, _token: token},
success:function(data){
//console.log(data);
$('#success_message').fadeIn().html(data);
}
});
/**Ajax code ends**/
});
});
</script>
So when click on submit button by entering some data then the output message(echo "welcome ". $name;) is printing. But when I click on submit button with empty text box then it does not print the error message from the controller and it throws a 422 (Unprocessable Entity) error in console. Why my approach is wrong here and how can I print the error message then. Please help. Thank you in advance.
因此,当通过输入一些数据单击提交按钮时,输出消息(echo "welcome ". $name;)正在打印。但是,当我单击带有空文本框的提交按钮时,它不会从控制器打印错误消息,并且会在控制台中引发 422(不可处理实体)错误。为什么我的方法在这里是错误的,然后我如何打印错误消息。请帮忙。先感谢您。
回答by Dexter Bengil
Your approach is actually not wrong, it just you needs to catch the error response on your ajax request as when Laravel validation failed, it throws an Error 422 (Unprocessable Entity)
with corresponding error messages.
您的方法实际上并没有错,只是您需要捕获 ajax 请求上的错误响应,因为当 Laravel 验证失败时,它会抛出Error 422 (Unprocessable Entity)
带有相应错误消息的消息。
/**Ajax code**/
$.ajax({
type: "post",
url: "{{ url('/verifydata') }}",
data: {name: name, _token: token},
dataType: 'json', // let's set the expected response format
success: function(data){
//console.log(data);
$('#success_message').fadeIn().html(data.message);
},
error: function (err) {
if (err.status == 422) { // when status code is 422, it's a validation issue
console.log(err.responseJSON);
$('#success_message').fadeIn().html(err.responseJSON.message);
// you can loop through the errors object and show it to the user
console.warn(err.responseJSON.errors);
// display errors on each form field
$.each(err.responseJSON.errors, function (i, error) {
var el = $(document).find('[name="'+i+'"]');
el.after($('<span style="color: red;">'+error[0]+'</span>'));
});
}
}
});
/**Ajax code ends**/
On your controller
在您的控制器上
public function testAjax(Request $request)
{
// this will automatically return a 422 error response when request is invalid
$this->validate($request, ['name' => 'required']);
// below is executed when request is valid
$name = $request->name;
return response()->json([
'message' => "Welcome $name"
]);
}
回答by apokryfos
Here's a better approach to validation:
这是一种更好的验证方法:
In your controller:
在您的控制器中:
public function testAjax(Request $request)
{
$this->validate($request, [ 'name' => 'required' ]);
return response("welcome ". $request->input('name'));
}
The framework then will create a validator for you and validate the request. It will throw a ValidationException
if it fails validation.
然后框架将为您创建一个验证器并验证请求。ValidationException
如果验证失败,它将抛出一个。
Assuming you have not overriden how the validation exception is rendered here's the default code the built-in exception handlerwill run
假设您没有覆盖验证异常的呈现方式,这里是内置异常处理程序将运行的默认代码
protected function convertValidationExceptionToResponse(ValidationException $e, $request)
{
if ($e->response) {
return $e->response;
}
$errors = $e->validator->errors()->getMessages();
if ($request->expectsJson()) {
return response()->json($errors, 422);
}
return redirect()->back()->withInput($request->input())->withErrors($errors);
}
Again this is handled for you by the framework.
同样,这由框架为您处理。
On the client side you should be able to do:
在客户端,您应该能够执行以下操作:
<script>
$(document).ready(function(){
$("#submit").click(function(){
var name = $("#name").val();
var token = $("#token").val();
/**Ajax code**/
$.ajax({
type: "post",
url:"{{URL::to('/verifydata')}}",
data:{name:name, _token: token},
success:function(data){
//console.log(data);
$('#success_message').fadeIn().html(data);
},
error: function (xhr) {
if (xhr.status == 422) {
var errors = JSON.parse(xhr.responseText);
if (errors.name) {
alert('Name is required'); // and so on
}
}
}
});
/**Ajax code ends**/
});
});
</script>