php Laravel 验证:检查验证器失败的原因
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25573617/
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 Validation: check why validator failed
提问by dcolumbus
If there a way to check whether or not the validator failed specifically because of the unique
rule?
如果有办法检查验证器是否因为unique
规则而失败?
$rules = array(
'email_address' => 'required|email|unique:users,email',
'postal_code' => 'required|alpha_num',
);
$messages = array(
'required' => 'The :attribute field is required',
'email' => 'The :attribute field is required',
'alpha_num' => 'The :attribute field must only be letters and numbers (no spaces)'
);
$validator = Validator::make(Input::all(), $rules, $messages);
if ($validator->fails()) {
In laymans terms, I basically want to know: "did the validation fail because the email_address was not unique?"
用外行的话来说,我基本上想知道:“验证失败是不是因为 email_address 不是唯一的?”
回答by Brian Dillingham
Check for a specific rule within the returned array of failed rules
检查返回的失败规则数组中的特定规则
if ($validator->fails()) {
$failedRules = $validator->failed();
if(isset($failedRules['email_address']['Unique'])) {
...
回答by Lynx
This will display an error and tell you what failed:
这将显示一个错误并告诉您失败的原因:
Controller
控制器
if($validation->fails()){
return Redirect::back()->withErrors($validation)->withInput();
}
foreach($errors->all() as $error) {
echo $error;
}
And in your blade template add this:
在您的刀片模板中添加以下内容:
@foreach($errors->all() as $error)
<div>
{{$error}}
</div>
@endforeach
And that will return a message with whatever the error is. Email doesn't match. Field is required. Blah blah
无论错误是什么,这都会返回一条消息。电子邮件不匹配。字段是必需的。胡说八道
You can also remove that email array from the $message. The validator will handle all that for you. You only want to use that if you want custom messages.
您还可以从 $message 中删除该电子邮件数组。验证器将为您处理所有这些。如果您想要自定义消息,您只想使用它。
You can also try to var_dump this statement:
你也可以尝试 var_dump 这个语句:
var_dump($validation->errors()); die;
var_dump($validation->errors()); 死;