0

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.

2 Answers 2

2

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".

Sign up to request clarification or add additional context in comments.

2 Comments

Just as an addition to this: i don't think there is a way to tell using the returned response which 'rule' failed, i.e. are you looking for something that says 'required' => false, 'confirmed' => true, as i don't think that exists.
Ok, thanks for your response Daniel. I will try to live with the default validation messages then and adjust the field names using the attributes array in validation.php in languages dir.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.