当变量为空时,Laravel 5.3验证失败 [英] Laravel 5.3 Validation Fails when Variables are Null

查看:121
本文介绍了当变量为空时,Laravel 5.3验证失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

自从laravel从5.1升级到5.3之后,我在Validation中遇到了一些奇怪的问题.

Since upgrading laravel from 5.1 to 5.3, I've got couple of odd issues with Validation.

当我发布这样的数据时:

When I post a data like this:

firstName    null

验证规则如下:

$validator = Validator::make($postData, [
              'firstName'           => 'string|max:255',
              'lastName'            => 'string|max:255'
            ]);

以上操作失败,并显示类似"The XYZ must be a string."的消息.我不明白的是:

The above fails with the messages something like "The XYZ must be a string.". What I don't understand is:

  1. 当未设置为required时,为什么验证失败? 意思是,它应该忽略它,并且如果值是 空的,对吧?

  1. Why is the validation failing when it is not set as required? Meaning, it should ignore it and not throw an error if the value is empty, right?

如果将值设置为null,为什么验证失败?

Why does the validation fail if the value is set as null?

当根本不发送参数时,为什么验证失败? (例如完全不发布的lastName)

Why does the validation fail when the parameter is not sent at all? (like the lastName which is not posted at all)

Laravel 5.3验证中是否有更改?

Has something changed in Laravel 5.3 validations?

推荐答案

添加 nullable 规则:

'firstName' => 'string|max:255|nullable',
'lastName' => 'string|max:255|nullable'

正在验证的字段可能是null.这在验证原始类型(例如可以包含null值的字符串和整数)时特别有用.

The field under validation may be null. This is particularly useful when validating primitive such as strings and integers that can contain null values.

这篇关于当变量为空时,Laravel 5.3验证失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆