6

尝试实现 Laravel 基于长度的验证时

'password' => array(
    'required',
    'alpha_dash',
    'Min:7'
)

并在我的视图中输出错误消息

{{
    $errors->first(
        'password',
        '<span class="error">:message</span>'
    )
}}

我明白了

Unhandled Exception
Message:
Array to string conversion
Location:
_avalog\laravel\messages.php on line 188
Stack Trace:
#0 _avalog\laravel\laravel.php(42): Laravel\Error::native(8, 'Array to string...', '_avalog...', 188)
#1 [internal function]: Laravel\{closure}(8, 'Array to string...', '_avalog...', 188, Array)
#2 _avalog\laravel\messages.php(188): str_replace(':message', Array, 'get('password', 'get()

调试,看来是真的。如果我print_r( $validation );

Laravel\Validator Object (
    [attributes] => Array (
        [username] => fred
        [email] =>
        [password] => asd
        [csrf_token] => DWg3CUfqtMZkIRfyZXNEqygvWUHsGS9SQMue2V4S
    )
    [errors] => Laravel\Messages Object (
        [messages] => Array (
            [email] => Array (
                [0] => The email field is required.
            )
            [password] => Array ( 
                [0] => Array (
                    [numeric] => The password must be at least 7.
                    [file] => The password must be at least 7 kilobytes.
                    [string] => The password must be at least 7 characters.
                )
            )
    )
    [format] => :message
)

您可以看到,messages 实际上包含一个密码数组,该数组似乎取决于输入类型,即使我在规则中指定它是 alphadash

[password] => Array (
    [0] => Array (
        [numeric] => The password must be at least 7.
        [file] => The password must be at least 7 kilobytes.
        [string] => The password must be at least 7 characters.
    )
)

而其余的,不要

[email] => Array (
    [0] => The email format is invalid.
)

messages.phpLaravel 框架中,它无法处理这种基于数组的消息传递,所以我假设我在它到达那里之前做错了什么,但我不知道是什么。

谢谢你的帮助。

4

2 回答 2

20

您的规则输入错误。它必须像

'password' => 'required|alpha_dash|min:7'

查看 Laravel 验证文档以获取更多信息

于 2013-03-18T00:48:15.517 回答
1

'password.min' => "密码不能少于6个字符。",

$custom_validation_messages = array(
  'password.min' => "Password can not be less than 6 characters.",
  'password.required' => "Password is required"
);

   $validator = Validator::make($data, [
                //'email'          => ['required','unique:users,email','email','max:255'],
   'email'          => ['required','email','max:255'],
   'password'       => 'required|min:6|confirmed'

 ],$custom_validation_messages);
于 2020-05-28T16:01:50.570 回答