gpt4 book ai didi

javascript - 如何在 laravel 中验证 X-editable 请求(服务器端)

转载 作者:行者123 更新时间:2023-12-01 03:26:37 25 4
gpt4 key购买 nike

我已经设法让 x-editable ( https://vitalets.github.io/x-editable/ ) 来处理页面,只要我单击一个字段,它就会内联显示,我可以编辑它,并且我能够成功提交到 POST URI。

这里的想法是我发送三个键值对:

array:3 [▼
"name" => "name"
"value" => "mathematics"
"pk" => "1"
]

我的 update() 方法捕获该数组,并成功更新数据库中的记录。但我无法验证数据。

这就是我的 Controller 的样子:

 public function update(Request $request)
{
//
$id = $request->pk;
$subject = Subject::findOrFail($id);

$rules = array (
'name' => 'bail|required|max:20|unique:subjects,name,'.$id
);

即使我尝试失败,此验证也很容易通过

    $validator = Validator::make ( $request->all(), $rules );

if ($validator->fails ()) {
return response()->json ( array (

'errors' => $validator->getMessageBag ()->toArray ()
) );
} else {
$subject->update([$request->name => $request->value]);
}
return response ()->json ( $subject );
}

所以就好像我没有将“正确的”Request 对象传递给 validate() ?没有表单提交,但是the documentation明确指出:

Laravel generates a JSON response containing all of the validation errors. This JSON response will be sent with a 422 HTTP status code.1

路线:

Route::post('/subjects/update/', 'SubjectsController@update');

脚本:

$('#subjects').editable({
container:'body',
selector:'td.name',
type:'post',
dataType:'JSON',
validate:function(value){
if ($.trim(value) === '') {
return "Field is required";
}
}
});
<小时/>

1 https://laravel.com/docs/5.4/validation#quick-ajax-requests-and-validation

最佳答案

如果我没记错的话,name 是要编辑的字段(DB 列),value 是值。您似乎正在更新 name 列,因此您必须验证请求中 value 的唯一性,而不是“name”。

此外,我建议您使用 Controller 的 validate 方法(由 ValidatesRequests 特征提供):

public function update(Request $request)
{
$id = $request->pk;
$subject = Subject::findOrFail($id);

$this->validate($request, [
'name' => 'required', // this should be the column to update
'value' => 'bail|required|max:20|unique:subjects,name,'.$id
];

$subject->update([$request->name => $request->value]);

return $subject;
}

此处 validate 将自动拒绝,并显示 422 代码和 JSON 响应中的验证错误。如果通过,将继续更新。 (return $subject 还会返回响应中对象的 JSON 表示形式。)

关于javascript - 如何在 laravel 中验证 X-editable 请求(服务器端),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44780698/

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