为什么 laravel 验证空字符串时验证不正确?

Why laravel validation not work correct when validate for empty string?

简介:

我已验证空字符串的请求值。

代码:

if(isset($request->name)) {
    $this->validate($request, [
        'name' => [
            function ($attribute, $value, $fail) {
                if (mb_strlen(preg_replace('/\s/', '', $value)) == 0) {
                    $fail($attribute.' is can't be empty.');
                }
            }
        ]
    ]);
    $user->name = $request->name;
    $user->save(); 
}

也厌倦了自定义规则。

规则代码:

public function passes($attribute, $value)
{
    $result = preg_replace('/\s/', '', $value);
    return mb_strlen($result) == 0 ? false : true;
}

/**
 * Get the validation error message.
 *
 * @return string
 */
public function message()
{
    return "Attribute value can't be empty string.";
}

规则测试代码:

if(isset($request->name)) {
    $this->validate($request, [
        'name' => [
            new IsEmptyString
        ]
    ]);
    $user->name= $request->name;
    $user->save(); 
}

问题:

哪里出错了?为什么 laravel 在检查空字符串的请求值时不发送验证错误消息?

谢谢!

删除 if() 条件。然后将 required 规则添加到验证中。

$this->validate($request, [
    'name' => ['required',
        function ($attribute, $value, $fail) {
            if (mb_strlen(preg_replace('/\s/', '', $value)) == 0) {
                $fail($attribute.' is can't be empty.');
            }
        }
    ]
]);
$user->name = $request->name;
$user->save(); 

根据您的情况,您必须将您的条件更改为:

if(array_key_exists('name', $request->all())) {

}

当您检查 isset($request->name) 并且此条件结果 return false 并且验证码甚至没有 运行 并且事实上条件 return 错误。

通常,您的工作代码如下所示:

if(array_key_exists('name', $request->all())) {
    $this->validate($request, [
        'name' => [
            'required',
            function ($attribute, $value, $fail) {
                if (mb_strlen(preg_replace('/\s/', '', $value)) == 0) {
                    $fail($attribute." is can't be empty.");
                }
            }
        ]
    ]);

    $user->name = $request->name;
    $user->save();  
}