gpt4 book ai didi

php - Laravel - 防止对空输入进行验证检查

转载 作者:可可西里 更新时间:2023-11-01 00:08:15 25 4
gpt4 key购买 nike

表单中有一些输入字段,这是我在模型中定义的规则:

  public static $rules = [
'name' => 'string',
'email' => 'email',
'phone' => 'sometimes|numeric',
'mobile' => 'numeric',
'site_type_id' => 'integer'
];

它们都不是必需的。但是当提交表单时,出现验证错误,即电子邮件应该是电子邮件地址,对于其他输入也是如此。
在这种情况下,有一个字段 required 是没有意义的,因为 laravel 总是根据规则验证字段。
我知道提交表单时空字段有一个 null 值。我应该如何防止对空字段进行字段验证?

最佳答案

Laravel 5.3 以后 nullable 可用于可选字段:

https://laravel.com/docs/validation#rule-nullable

you will often need to mark your "optional" request fields as nullable if you do not want the validator to consider null values as invalid

所以 rules 数组应该是这样的:

public static $rules = [
'name' => 'nullable|string',
'email' => 'nullable|email',
'phone' => 'nullable|numeric',
'mobile' => 'nullable|numeric',
'site_type_id' => 'nullable|integer'
];

关于php - Laravel - 防止对空输入进行验证检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42887617/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com