06.10.2016 Views

laravel-5

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Validation 490<br />

20 }<br />

21 }<br />

AJAX Requests & Validation<br />

In this example, we used a traditional form to send data to the application. However, many<br />

applications use AJAX requests. When using the validate method during an AJAX request, Laravel<br />

will not generate a redirect response. Instead, Laravel generates a JSON response containing all of<br />

the validation errors. This JSON response will be sent with a 422 HTTP status code.<br />

Validating Arrays<br />

Validating array form input fields doesn’t have to be a pain. For example, to validate that each e-mail<br />

in a given array input field is unique, you may do the following:<br />

1 $validator = Validator::make($request->all(), [<br />

2 'person.*.email' => 'email|unique:users',<br />

3 'person.*.first_name' => 'required_with:person.*.last_name',<br />

4 ]);<br />

Likewise, you may use the * character when specifying your validation messages in your language<br />

files, making it a breeze to use a single validation message for array based fields:<br />

1 'custom' => [<br />

2 'person.*.email' => [<br />

3 'unique' => 'Each person must have a unique e-mail address',<br />

4 ]<br />

5 ],<br />

Other Validation Approaches<br />

Manually Creating Validators<br />

If you do not want to use the ValidatesRequests trait’s validate method, you may create a<br />

validator instance manually using the Validator facade. The make method on the facade generates<br />

a new validator instance:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!