Laravel:表单验证字符串长度错误消息导致异常

时间:2013-03-17 17:35:22

标签: php validation laravel laravel-3

尝试实施基于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
)

你可以看到消息实际上包含一个密码数组,它似乎依赖于输入类型,即使我在规则中指定它是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.
)

在Laravel框架中查看messages.php,它没有任何东西可以处理这种基于数组的消息传递,因此我认为在它到达之前我做错了什么,但我不知道是什么。

感谢您的帮助。

2 个答案:

答案 0 :(得分:14)

您的规则条目错误。它必须像

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

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

答案 1 :(得分: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);