Laravel 有时 vs 有时|需要
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35839414/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel sometimes vs sometimes|required
提问by amin
What is the difference between sometimes|required|email
and sometimes|email
in Laravel validation?I've read this discussion from laracastsbut still it is ambiguous for me
Laravel 验证sometimes|required|email
和sometimes|email
Laravel 验证之间有什么区别?我已经从 laracasts 中阅读了这个讨论,但对我来说仍然不明确
回答by haakym
From the docs:
从文档:
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-adding-rules
https://laravel.com/docs/5.2/validation#conditionally-adding-rules
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.
如果我可以简化它,我会说sometimes
意味着,如果该字段出现在请求中,则仅应用其余的验证规则。想象一下sometimes
,就像一个 if 语句,它在应用任何规则之前检查请求/输入中是否存在该字段。
I use this rule when I have some javascript on a page that will disablea 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.
当我在页面上有一些 javascript 会禁用一个字段时,我使用这个规则,因为当一个字段被禁用时,它不会显示在请求中。如果我只是说required|email
验证器总是要应用规则,而使用sometimes
规则只会应用验证,如果该字段出现在请求中!希望这是有道理的。
Examples:
例子:
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!