Laravel 中的数据验证无效

Data validation in Laravel is not working

我在我的项目中创建了一个自定义请求,但不知何故它不起作用。我面临两个错误。如果通过 Ajax.

验证失败,我正在尝试在视图中显示一条消息

1) 422 Unprocessable Entity error

2) Undefined variable: teacherrequest

我在请求文件夹中设置的验证规则,

TeacherRequest.php:

public function rules()
{
    return [
        'Name' => 'required|regex:/^[\pL\s\-]+$/u',
        'FName' => 'required|regex:/^[\pL\s\-]+$/u',
    ];
}

控制器:

public function update(TeacherRequest $request, $id)
{
    if ($teacherrequest->fails()) {
        return response()->json([
            'msg' => 'Please Enter Correct Data',
        ]);
    }
}

AJAX:

success: function (data) {

if(data.msg){
        alert("please validate data");

}
}

更新:

如果我删除 if 条件,我会收到 422 错误,如何在视图中显示该错误?

您将 TeacherRequest 定义为 $request TeacherRequest $request

但在下一行将其用作

if ($teacherrequest->fails()){ // this is wrong

正确的应该这样定义

TeacherRequest $teacherrequest

或者如果你没有更改依赖注入,只需像这样更改验证器

if ($request->fails()){

总结:为什么会发生错误已经具体解释了未定义的teacherrequest变量,因此上面的2个解决方案可以解决它

如果您键入提示 class 作为控制器操作方法中的参数(就像您在上面的示例中所做的那样)Laravel 将自动 运行 您的验证规则和return 如果验证失败则 422 Unprocessable Entity。您不需要像上面那样手动检查验证是否失败;在您的控制器的 update 方法中,您可以在验证通过时实现您想要 运行 的逻辑。

同样在您的前端,您需要使用 error ajax 回调来显示错误消息,因为 422 状态代码不被视为成功。

请参阅 documentation 创建表单请求。

So, how are the validation rules evaluated? All you need to do is type-hint the request on your controller method. The incoming form request is validated before the controller method is called, meaning you do not need to clutter your controller with any validation logic.

首先,public function update(TeacherRequest $request) 所以在函数中你需要使用 $request 而不是 $teacherrequest

其次您需要 public function authorize() 返回 true。