Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How validation rules work in laravel

In laravel, in order to validate some input from user, we can use Validator Class.

for example for a registration by email , validation rule can be:

array( 'email' => 'required|email|unique:users,email' )

Which says, email is required, email should be in email format, and should not registered in table users before. ( should be unique )

So, How does this work?

Does it use short-circuit ? If we go through step by step

  • it checks if input is set by required
    if Passed, jumps to next rule
  • then checks if it is in email format
    if Passed, jumps to next rule
  • checks if not exists in table users

I asked someone and he said , it check all , goes through all rules.
If required rule is not passed, there is no reason to check if input is in email format.
And if it is not in email format, there is no need to check database.

Does anyone know how it work?

like image 670
Pars Avatar asked Dec 19 '13 22:12

Pars


People also ask

How does Laravel validation work?

When using the validate method during an AJAX request, Laravel will not generate a redirect response. Instead, Laravel generates a JSON response containing all of the validation errors. This JSON response will be sent with a 422 HTTP status code.

How do you add a validation rule in Laravel?

You should add all your validation logic in the passes() function. It should return true or false based on the logic you have written in the function. The message() function returns a string that specifies the error message to be displayed in case the validation fails.


2 Answers

This depends on the rule. In practice, Laravel will stop processing other rules if the required attribute is failed. However, if required passes, it will continue to validate other rules.

This means you can receive multiple Validation Errors on the same field.

like image 65
James Binford Avatar answered Oct 26 '22 23:10

James Binford


I could not find details for Laravel 4, but the Laravel 5.4 documentation implies that all validation rules are run in order without short-circuit evaluation.

In Laravel 5, you can force short-circuit evaluation by prefixing 'bail' to the validation rule.

$this->validate($request, [
    'title' => 'bail|required|unique:posts|max:255',
    'body' => 'required',
]);

I came here looking for why short-circuiting would be off by default, I think James is correct in his reasoning that it is for receiving multiple validation errors on the same field.

like image 29
Ron Avatar answered Oct 26 '22 22:10

Ron