Laravel有时vs有时|必填 [英] Laravel sometimes vs sometimes|required
问题描述
在Laravel验证中,有时|必需|电子邮件
和有时|电子邮件
之间有什么区别?我读过
What is the difference between sometimes|required|email
and sometimes|email
in Laravel validation?I've read this discussion from laracasts but still it is ambiguous for me
推荐答案
来自文档:
在某些情况下,您可能希望针对仅当输入数组中存在该字段时,才使用该字段.要快为此,请将有时会的规则添加到您的规则列表中
In some situations, you may wish to run validation checks against a field only if that field is present in the input array. To quickly accomplish this, add the sometimes rule to your rule list
https://laravel.com/docs/5.2/validation#conditionally-添加规则
如果我可以简化一下,我会说有时
的意思是,仅当请求中显示该字段时,才应用其余的验证规则.想象有时
就像一条if语句,该语句在应用任何规则之前检查请求/输入中是否存在该字段.
If I could simplify it, I would say sometimes
means, only apply the rest of the validation rules if the field shows up in the request. Imagine sometimes
is like an if statement that checks if the field is present in the request/input before applying any of the rules.
当页面上有一些JavaScript会禁用时,我会使用此规则,因为禁用某个字段时,它将不会显示在请求中.如果我只是说 required | email
,验证器将始终应用规则,而使用 stimes
规则仅在请求中显示该字段时才应用验证!希望有道理.
I use this rule when I have some javascript on a page that will disable a field, as when a field is disabled it won't show up in the request. If I simply said required|email
the validator is always going to apply the rules whereas using the sometimes
rule will only apply the validation if the field shows up in the request! Hope that makes sense.
示例:
input: []
rules: ['email' => 'sometimes|required|email']
result: pass, the request is empty so sometimes won't apply any of the rules
input: ['email' => '']
rules: ['email' => 'sometimes|required|email']
result: fail, the field is present so the required rule fails!
input: []
rules: ['email' => 'required|email']
result: fail, the request is empty and we require the email field!
这篇关于Laravel有时vs有时|必填的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!