问题
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?
I quite new to laravel as I began working with it a week ago so I hope someone may shed some light on this.
回答1:
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()
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".
回答2:
You can get error messages for a given attribute:
$errors = $validation->errors->get('email');
and then loop through the errors
foreach ($errors as $error) {
print $error;
}
or get all the error messages
$errors = $validation->errors->all();
then loop through the error messages
foreach ($errors as $error) {
print $error;
}
You can see more information about laravel validation here
来源:https://stackoverflow.com/questions/14455112/distinguish-between-validation-errors-in-laravel