Composite Validation Rules

News

June 25th, 2019

composite-validation-rule.png

Validation Composite is a package by Paul Klimov that allows uniting several validation rules into a single one for easy reuse.

Here are a few simple examples that will help visualize how this package works. Let’s say you want to centralize your password or avatar rules into one composite rule:

1<?php
2
3namespace App\Rules;
4
5use Illuminatech\Validation\Composite\CompositeRule;
6
7class PasswordRule extends CompositeRule
8{
9 protected function rules(): array
10 {
11 return ['string', 'min:8', 'max:200'];
12 }
13}
14
15class AvatarRule extends CompositeRule
16{
17 protected function rules(): array
18 {
19 return ['file', 'mimes:png,jpg,jpeg', 'max:1024'];
20 }
21}

Example usage of these composite rules looks like this in a controller:

1public function update(Request $request)
2{
3 $validatedData = $request->validate([
4 'password' => ['required', new PasswordRule],
5 'avatar' => ['required', new AvatarRule],
6 // ...
7 ]);
8
9 // ...
10}

You can learn more about this package, get full installation instructions, and view the source code on GitHub at illuminatech/validation-composite.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.

Laravel News Partners