Distinguish between validation errors in Laravel

旧街凉风 提交于 2019-12-08 11:20:58

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!