【问题标题】:Loop through validation errors, and display the right one - Laravel 5.2循环验证错误,并显示正确的错误 - Laravel 5.2
【发布时间】:2016-11-30 19:42:04
【问题描述】:

我有一个注册系统,我需要显示出现的任何验证错误。我的大部分验证都由 JavaScript 检查,因为我使用的是 Semantic-UI 框架。但是有 2 条自定义验证规则我无法在 JavaScript 中真正显示,所以我需要查看这两条错误消息中的哪一条,并闪现正确的错误消息。

这是我的注册函数和验证:

 public function postRegister (Request $request) {

        $validator = Validator::make($request->all(), [
            'username' => 'unique:users',
            'email'    => 'unique:users',
            'password' => '',
        ]);

        if ($validator->fails()) {
            flash()->error('Error', 'Either your username or email is already take. Please choose a different one.');
            return back();
        }

        // Create the user in the Database.
        User::create([
            'email' => $request->input('email'),
            'username' => $request->input('username'),
            'password' => bcrypt($request->input('password')),
            'verified' => 0,
        ]);

        // Flash a info message saying you need to confirm your email.
        flash()->overlay('Info', 'You have successfully registered. Please confirm your email address in your inbox.');

        return redirect()->back();

如您所见,有两条自定义错误消息,如果用户只发现其中一条错误,它会在我的 Sweet-alert 模式中显示该消息。

我怎样才能遍历我的错误消息并查看我错了,并针对该错误显示特定的 Flash 消息?

【问题讨论】:

  • 你可以简单地解析 $validator->messages()

标签: php validation laravel laravel-5.2


【解决方案1】:

要检索所有验证器错误的数组,您可以使用errors 方法:

$messages = $validator->errors();
//Determining If Messages Exist For A Field
if ($messages->has('username')) {
    //Show custom message
}
if ($messages->has('email')) {
    //Show custom message
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-28
    • 2016-08-06
    • 1970-01-01
    • 2016-05-25
    • 2016-09-12
    • 1970-01-01
    • 2023-04-01
    • 2018-12-05
    相关资源
    最近更新 更多