区分Laravel中的验证错误 [英] Distinguish between validation errors in Laravel
问题描述
我正在使用Laravel 4中的验证规则,该规则非常强大.但是,我不知道如何区分可能发生的不同验证错误.例如,如果我使用以下规则:
I'm using the validation rules in Laravel 4, which are very powerful. However, I wonder how one can distinguish between the different validations error that may occur. For example if I use the following rules:
$rules = array(
'email' => 'required|email|confirmed',
'email_confirmation' => 'required|email',
);
我如何知道触发某个字段错误的验证规则/规则?我可以通过某种方式判断出该错误是由于缺少电子邮件值,电子邮件不是有效的电子邮件地址和/或无法确认电子邮件引起的吗?
How can I tell what validation rule/rules that triggered the error for a certain field? Is there some way I can tell that the error was due to a missing email value, email wasn't a valid email address and/or the email couldn't be confirmed?
一周前开始使用laravel时,我还很陌生,所以我希望有人对此有所了解.
I quite new to laravel as I began working with it a week ago so I hope someone may shed some light on this.
推荐答案
由验证实例返回的验证消息应持有知道发生了什么问题的关键.
The validation messages returned by the validation instance should hold the key to knowing what went wrong.
您可以使用以下方法访问验证器对象给出的消息:
You can access the messages given by the validator object by using:
$messages = $validator->messages(); // Where $validator is your validator instance.
$messages = $messages->all()
这应该为您提供一个MessageBag
对象的实例,您可以使用foreach循环对其进行遍历:
That should give you an instance of a MessageBag
object, that you can run through with a foreach loop:
foreach ($messages as $message) {
print $message;
}
在其中,您应该找到答案,即,将显示一条消息,内容为:电子邮件确认必须与'电子邮件'字段匹配".
And inside there, you should find your answer, i.e. there will be a message saying something like: "Email confirmation must match the 'email' field".
这篇关于区分Laravel中的验证错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!