PluginProbe
WPIDE – File Manager & Code Editor / 3.5.9
WPIDE – File Manager & Code Editor v3.5.9
3.5.9 3.5.8 3.5.7 2.0.14 2.0.15 2.0.16 2.0.2 2.0.4 2.0.5 2.0.6 2.0.7 2.0.8 2.0.9 2.1 2.2 2.3 2.3.1 2.3.2 2.4.0 2.5 2.6 3.0 3.1 3.2 3.3 All 55 releases
wpide / vendor / rakit / validation / README.md

README.md in WPIDE – File Manager & Code Editor 3.5.9, at vendor/rakit/validation/README.md

1,169 lines 31.0 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 Rakit Validation - PHP Standalone Validation Library
2 ======================================================
3
4 [](https://travis-ci.org/rakit/validation![Build Status](https://img.shields.io/travis/rakit/validation.svg?style=flat-square)](https://travis-ci.org/rakit/validation](https://travis-ci.org/rakit/validation)
5 [](https://coveralls.io/github/rakit/validation![Coverage Status](https://coveralls.io/repos/github/rakit/validation/badge.svg?branch=setup_coveralls)](https://coveralls.io/github/rakit/validation](https://coveralls.io/github/rakit/validation)
6 [](http://doge.mit-license.org![License](http://img.shields.io/:license-mit-blue.svg?style=flat-square)](http://doge.mit-license.org](http://doge.mit-license.org)
7
8
9 PHP Standalone library for validating data. Inspired by `Illuminate\Validation` Laravel.
10
11 ## Features
12
13 * API like Laravel validation.
14 * Array validation.
15 * `$_FILES` validation with multiple file support.
16 * Custom attribute aliases.
17 * Custom validation messages.
18 * Custom rule.
19
20 ## Requirements
21
22 * PHP 7.0 or higher
23 * Composer for installation
24
25 ## Quick Start
26
27 #### Installation
28
29 ```
30 composer require "rakit/validation"
31 ```
32
33 #### Usage
34
35 There are two ways to validating data with this library. Using `make` to make validation object,
36 then validate it using `validate`. Or just use `validate`.
37 Examples:
38
39 Using `make`:
40
41 ```php
42 <?php
43
44 require('vendor/autoload.php');
45
46 use Rakit\Validation\Validator;
47
48 $validator = new Validator;
49
50 // make it
51 $validation = $validator->make($_POST + $_FILES, [
52 'name' => 'required',
53 'email' => 'required|email',
54 'password' => 'required|min:6',
55 'confirm_password' => 'required|same:password',
56 'avatar' => 'required|uploaded_file:0,500K,png,jpeg',
57 'skills' => 'array',
58 'skills.*.id' => 'required|numeric',
59 'skills.*.percentage' => 'required|numeric'
60 ]);
61
62 // then validate
63 $validation->validate();
64
65 if ($validation->fails()) {
66 // handling errors
67 $errors = $validation->errors();
68 echo "<pre>";
69 print_r($errors->firstOfAll());
70 echo "</pre>";
71 exit;
72 } else {
73 // validation passes
74 echo "Success!";
75 }
76
77 ```
78
79 or just `validate` it:
80
81 ```php
82 <?php
83
84 require('vendor/autoload.php');
85
86 use Rakit\Validation\Validator;
87
88 $validator = new Validator;
89
90 $validation = $validator->validate($_POST + $_FILES, [
91 'name' => 'required',
92 'email' => 'required|email',
93 'password' => 'required|min:6',
94 'confirm_password' => 'required|same:password',
95 'avatar' => 'required|uploaded_file:0,500K,png,jpeg',
96 'skills' => 'array',
97 'skills.*.id' => 'required|numeric',
98 'skills.*.percentage' => 'required|numeric'
99 ]);
100
101 if ($validation->fails()) {
102 // handling errors
103 $errors = $validation->errors();
104 echo "<pre>";
105 print_r($errors->firstOfAll());
106 echo "</pre>";
107 exit;
108 } else {
109 // validation passes
110 echo "Success!";
111 }
112
113 ```
114
115 In this case, 2 examples above will output the same results.
116
117 But with `make` you can setup something like custom invalid message, custom attribute alias, etc before validation running.
118
119 ### Attribute Alias
120
121 By default we will transform your attribute into more readable text. For example `confirm_password` will be displayed as `Confirm password`.
122 But you can set it anything you want with `setAlias` or `setAliases` method.
123
124 Example:
125
126 ```php
127 $validator = new Validator;
128
129 // To set attribute alias, you should use `make` instead `validate`.
130 $validation->make([
131 'province_id' => $_POST['province_id'],
132 'district_id' => $_POST['district_id']
133 ], [
134 'province_id' => 'required|numeric',
135 'district_id' => 'required|numeric'
136 ]);
137
138 // now you can set aliases using this way:
139 $validation->setAlias('province_id', 'Province');
140 $validation->setAlias('district_id', 'District');
141
142 // or this way:
143 $validation->setAliases([
144 'province_id' => 'Province',
145 'district_id' => 'District'
146 ]);
147
148 // then validate it
149 $validation->validate();
150
151 ```
152
153 Now if `province_id` value is empty, error message would be 'Province is required'.
154
155 ## Custom Validation Message
156
157 Before register/set custom messages, here are some variables you can use in your custom messages:
158
159 * `:attribute`: will replaced into attribute alias.
160 * `:value`: will replaced into stringify value of attribute. For array and object will replaced to json.
161
162 And also there are several message variables depends on their rules.
163
164 Here are some ways to register/set your custom message(s):
165
166 #### Custom Messages for Validator
167
168 With this way, anytime you make validation using `make` or `validate` it will set your custom messages for it.
169 It is useful for localization.
170
171 To do this, you can set custom messages as first argument constructor like this:
172
173 ```php
174 $validator = new Validator([
175 'required' => ':attribute harus diisi',
176 'email' => ':email tidak valid',
177 // etc
178 ]);
179
180 // then validation belows will use those custom messages
181 $validation_a = $validator->validate($dataset_a, $rules_for_a);
182 $validation_b = $validator->validate($dataset_b, $rules_for_b);
183
184 ```
185
186 Or using `setMessages` method like this:
187
188 ```php
189 $validator = new Validator;
190 $validator->setMessages([
191 'required' => ':attribute harus diisi',
192 'email' => ':email tidak valid',
193 // etc
194 ]);
195
196 // now validation belows will use those custom messages
197 $validation_a = $validator->validate($dataset_a, $rules_for_dataset_a);
198 $validation_b = $validator->validate($dataset_b, $rules_for_dataset_b);
199
200 ```
201
202 #### Custom Messages for Validation
203
204 Sometimes you may want to set custom messages for specific validation.
205 To do this you can set your custom messages as 3rd argument of `$validator->make` or `$validator->validate` like this:
206
207 ```php
208 $validator = new Validator;
209
210 $validation_a = $validator->validate($dataset_a, $rules_for_dataset_a, [
211 'required' => ':attribute harus diisi',
212 'email' => ':email tidak valid',
213 // etc
214 ]);
215
216 ```
217
218 Or you can use `$validation->setMessages` like this:
219
220 ```php
221 $validator = new Validator;
222
223 $validation_a = $validator->make($dataset_a, $rules_for_dataset_a);
224 $validation_a->setMessages([
225 'required' => ':attribute harus diisi',
226 'email' => ':email tidak valid',
227 // etc
228 ]);
229
230 ...
231
232 $validation_a->validate();
233 ```
234
235 #### Custom Message for Specific Attribute Rule
236
237 Sometimes you may want to set custom message for specific rule attribute.
238 To do this you can use `:` as message separator or using chaining methods.
239
240 Examples:
241
242 ```php
243 $validator = new Validator;
244
245 $validation_a = $validator->make($dataset_a, [
246 'age' => 'required|min:18'
247 ]);
248
249 $validation_a->setMessages([
250 'age:min' => '18+ only',
251 ]);
252
253 $validation_a->validate();
254 ```
255
256 Or using chaining methods:
257
258 ```php
259 $validator = new Validator;
260
261 $validation_a = $validator->make($dataset_a, [
262 'photo' => [
263 'required',
264 $validator('uploaded_file')->fileTypes('jpeg|png')->message('Photo must be jpeg/png image')
265 ]
266 ]);
267
268 $validation_a->validate();
269 ```
270
271 ## Translation
272
273 Translation is different with custom messages.
274 Translation may needed when you use custom message for rule `in`, `not_in`, `mimes`, and `uploaded_file`.
275
276 For example if you use rule `in:1,2,3` we will set invalid message like "The Attribute only allows '1', '2', or '3'"
277 where part "'1', '2', or '3'" is comes from ":allowed_values" tag.
278 So if you have custom Indonesian message ":attribute hanya memperbolehkan :allowed_values",
279 we will set invalid message like "Attribute hanya memperbolehkan '1', '2', or '3'" which is the "or" word is not part of Indonesian language.
280
281 So, to solve this problem, we can use translation like this:
282
283 ```php
284 // Set translation for words 'and' and 'or'.
285 $validator->setTranslations([
286 'and' => 'dan',
287 'or' => 'atau'
288 ]);
289
290 // Set custom message for 'in' rule
291 $validator->setMessage('in', ":attribute hanya memperbolehkan :allowed_values");
292
293 // Validate
294 $validation = $validator->validate($inputs, [
295 'nomor' => 'in:1,2,3'
296 ]);
297
298 $message = $validation->errors()->first('nomor'); // "Nomor hanya memperbolehkan '1', '2', atau '3'"
299 ```
300
301 > Actually, our built-in rules only use words 'and' and 'or' that you may need to translates.
302
303 ## Working with Error Message
304
305 Errors messages are collected in `Rakit\Validation\ErrorBag` object that you can get it using `errors()` method.
306
307 ```php
308 $validation = $validator->validate($inputs, $rules);
309
310 $errors = $validation->errors(); // << ErrorBag
311 ```
312
313 Now you can use methods below to retrieves errors messages:
314
315 #### `all(string $format = ':message')`
316
317 Get all messages as flatten array.
318
319 Examples:
320
321 ```php
322 $messages = $errors->all();
323 // [
324 // 'Email is not valid email',
325 // 'Password minimum 6 character',
326 // 'Password must contains capital letters'
327 // ]
328
329 $messages = $errors->all('<li>:message</li>');
330 // [
331 // '<li>Email is not valid email</li>',
332 // '<li>Password minimum 6 character</li>',
333 // '<li>Password must contains capital letters</li>'
334 // ]
335 ```
336
337 #### `firstOfAll(string $format = ':message', bool $dotNotation = false)`
338
339 Get only first message from all existing keys.
340
341 Examples:
342
343 ```php
344 $messages = $errors->firstOfAll();
345 // [
346 // 'email' => Email is not valid email',
347 // 'password' => 'Password minimum 6 character',
348 // ]
349
350 $messages = $errors->firstOfAll('<li>:message</li>');
351 // [
352 // 'email' => '<li>Email is not valid email</li>',
353 // 'password' => '<li>Password minimum 6 character</li>',
354 // ]
355 ```
356
357 Argument `$dotNotation` is for array validation.
358 If it is `false` it will return original array structure, if it `true` it will return flatten array with dot notation keys.
359
360 For example:
361
362 ```php
363 $messages = $errors->firstOfAll(':message', false);
364 // [
365 // 'contacts' => [
366 // 1 => [
367 // 'email' => 'Email is not valid email',
368 // 'phone' => 'Phone is not valid phone number'
369 // ],
370 // ],
371 // ]
372
373 $messages = $errors->firstOfAll(':message', true);
374 // [
375 // 'contacts.1.email' => 'Email is not valid email',
376 // 'contacts.1.phone' => 'Email is not valid phone number',
377 // ]
378 ```
379
380 #### `first(string $key)`
381
382 Get first message from given key. It will return `string` if key has any error message, or `null` if key has no errors.
383
384 For example:
385
386 ```php
387 if ($emailError = $errors->first('email')) {
388 echo $emailError;
389 }
390 ```
391
392 #### `toArray()`
393
394 Get all messages grouped by it's keys.
395
396 For example:
397
398 ```php
399 $messages = $errors->toArray();
400 // [
401 // 'email' => [
402 // 'Email is not valid email'
403 // ],
404 // 'password' => [
405 // 'Password minimum 6 character',
406 // 'Password must contains capital letters'
407 // ]
408 // ]
409 ```
410
411 #### `count()`
412
413 Get count messages.
414
415 #### `has(string $key)`
416
417 Check if given key has an error. It returns `bool` if a key has an error, and otherwise.
418
419
420 ## Getting Validated, Valid, and Invalid Data
421
422 For example you have validation like this:
423
424 ```php
425 $validation = $validator->validate([
426 'title' => 'Lorem Ipsum',
427 'body' => 'Lorem ipsum dolor sit amet ...',
428 'published' => null,
429 'something' => '-invalid-'
430 ], [
431 'title' => 'required',
432 'body' => 'required',
433 'published' => 'default:1|required|in:0,1',
434 'something' => 'required|numeric'
435 ]);
436 ```
437
438 You can get validated data, valid data, or invalid data using methods in example below:
439
440 ```php
441 $validatedData = $validation->getValidatedData();
442 // [
443 // 'title' => 'Lorem Ipsum',
444 // 'body' => 'Lorem ipsum dolor sit amet ...',
445 // 'published' => '1' // notice this
446 // 'something' => '-invalid-'
447 // ]
448
449 $validData = $validation->getValidData();
450 // [
451 // 'title' => 'Lorem Ipsum',
452 // 'body' => 'Lorem ipsum dolor sit amet ...',
453 // 'published' => '1'
454 // ]
455
456 $invalidData = $validation->getInvalidData();
457 // [
458 // 'something' => '-invalid-'
459 // ]
460 ```
461
462 ## Available Rules
463
464 > Click to show details.
465
466 <details><summary><strong>required</strong></summary>
467
468 The field under this validation must be present and not 'empty'.
469
470 Here are some examples:
471
472 | Value | Valid |
473 | ------------- | ----- |
474 | `'something'` | true |
475 | `'0'` | true |
476 | `0` | true |
477 | `[0]` | true |
478 | `[null]` | true |
479 | null | false |
480 | [] | false |
481 | '' | false |
482
483 For uploaded file, `$_FILES['key']['error']` must not `UPLOAD_ERR_NO_FILE`.
484
485 </details>
486
487 <details><summary><strong>required_if</strong>:another_field,value_1,value_2,...</summary>
488
489 The field under this rule must be present and not empty if the anotherfield field is equal to any value.
490
491 For example `required_if:something,1,yes,on` will be required if `something` value is one of `1`, `'1'`, `'yes'`, or `'on'`.
492
493 </details>
494
495 <details><summary><strong>required_unless</strong>:another_field,value_1,value_2,...</summary>
496
497 The field under validation must be present and not empty unless the anotherfield field is equal to any value.
498
499 </details>
500
501 <details><summary><strong>required_with</strong>:field_1,field_2,...</summary>
502
503 The field under validation must be present and not empty only if any of the other specified fields are present.
504
505 </details>
506
507 <details><summary><strong>required_without</strong>:field_1,field_2,...</summary>
508
509 The field under validation must be present and not empty only when any of the other specified fields are not present.
510
511 </details>
512
513 <details><summary><strong>required_with_all</strong>:field_1,field_2,...</summary>
514
515 The field under validation must be present and not empty only if all of the other specified fields are present.
516
517 </details>
518
519 <details><summary><strong>required_without_all</strong>:field_1,field_2,...</summary>
520
521 The field under validation must be present and not empty only when all of the other specified fields are not present.
522
523 </details>
524
525 <details><summary><strong>uploaded_file</strong>:min_size,max_size,extension_a,extension_b,...</summary>
526
527 This rule will validate data from `$_FILES`.
528 Field under this rule must be follows rules below to be valid:
529
530 * `$_FILES['key']['error']` must be `UPLOAD_ERR_OK` or `UPLOAD_ERR_NO_FILE`. For `UPLOAD_ERR_NO_FILE` you can validate it with `required` rule.
531 * If min size is given, uploaded file size **MUST NOT** be lower than min size.
532 * If max size is given, uploaded file size **MUST NOT** be higher than max size.
533 * If file types is given, mime type must be one of those given types.
534
535 Here are some example definitions and explanations:
536
537 * `uploaded_file`: uploaded file is optional. When it is not empty, it must be `ERR_UPLOAD_OK`.
538 * `required|uploaded_file`: uploaded file is required, and it must be `ERR_UPLOAD_OK`.
539 * `uploaded_file:0,1M`: uploaded file size must be between 0 - 1 MB, but uploaded file is optional.
540 * `required|uploaded_file:0,1M,png,jpeg`: uploaded file size must be between 0 - 1MB and mime types must be `image/jpeg` or `image/png`.
541
542 Optionally, if you want to have separate error message between size and type validation.
543 You can use `mimes` rule to validate file types, and `min`, `max`, or `between` to validate it's size.
544
545 For multiple file upload, PHP will give you undesirable array `$_FILES` structure ([here](http://php.net/manual/en/features.file-upload.multiple.php#53240) is the topic). So we make `uploaded_file` rule to automatically resolve your `$_FILES` value to be well-organized array structure. That means, you cannot only use `min`, `max`, `between`, or `mimes` rules to validate multiple file upload. You should put `uploaded_file` just to resolve it's value and make sure that value is correct uploaded file value.
546
547 For example if you have input files like this:
548
549 ```html
550 <input type="file" name="photos[]"/>
551 <input type="file" name="photos[]"/>
552 <input type="file" name="photos[]"/>
553 ```
554
555 You can simply validate it like this:
556
557 ```php
558 $validation = $validator->validate($_FILES, [
559 'photos.*' => 'uploaded_file:0,2M,jpeg,png'
560 ]);
561
562 // or
563
564 $validation = $validator->validate($_FILES, [
565 'photos.*' => 'uploaded_file|max:2M|mimes:jpeg,png'
566 ]);
567 ```
568
569 Or if you have input files like this:
570
571 ```html
572 <input type="file" name="images[profile]"/>
573 <input type="file" name="images[cover]"/>
574 ```
575
576 You can validate it like this:
577
578 ```php
579 $validation = $validator->validate($_FILES, [
580 'images.*' => 'uploaded_file|max:2M|mimes:jpeg,png',
581 ]);
582
583 // or
584
585 $validation = $validator->validate($_FILES, [
586 'images.profile' => 'uploaded_file|max:2M|mimes:jpeg,png',
587 'images.cover' => 'uploaded_file|max:5M|mimes:jpeg,png',
588 ]);
589 ```
590
591 Now when you use `getValidData()` or `getInvalidData()` you will get well array structure just like single file upload.
592
593 </details>
594
595 <details><summary><strong>mimes</strong>:extension_a,extension_b,...</summary>
596
597 The `$_FILES` item under validation must have a MIME type corresponding to one of the listed extensions.
598
599 </details>
600
601 <details><summary><strong>default/defaults</strong></summary>
602
603 This is special rule that doesn't validate anything.
604 It just set default value to your attribute if that attribute is empty or not present.
605
606 For example if you have validation like this
607
608 ```php
609 $validation = $validator->validate([
610 'enabled' => null
611 ], [
612 'enabled' => 'default:1|required|in:0,1'
613 'published' => 'default:0|required|in:0,1'
614 ]);
615
616 $validation->passes(); // true
617
618 // Get the valid/default data
619 $valid_data = $validation->getValidData();
620
621 $enabled = $valid_data['enabled'];
622 $published = $valid_data['published'];
623 ```
624
625 Validation passes because we sets default value for `enabled` and `published` to `1` and `0` which is valid. Then we can get the valid/default data.
626
627 </details>
628
629 <details><summary><strong>email</strong></summary>
630
631 The field under this validation must be valid email address.
632
633 </details>
634
635 <details><summary><strong>uppercase</strong></summary>
636
637 The field under this validation must be valid uppercase.
638
639 </details>
640
641 <details><summary><strong>lowercase</strong></summary>
642
643 The field under this validation must be valid lowercase.
644
645 </details>
646
647 <details><summary><strong>json</strong></summary>
648
649 The field under this validation must be valid JSON string.
650
651 </details>
652
653 <details><summary><strong>alpha</strong></summary>
654
655 The field under this rule must be entirely alphabetic characters.
656
657 </details>
658
659 <details><summary><strong>numeric</strong></summary>
660
661 The field under this rule must be numeric.
662
663 </details>
664
665 <details><summary><strong>alpha_num</strong></summary>
666
667 The field under this rule must be entirely alpha-numeric characters.
668
669 </details>
670
671 <details><summary><strong>alpha_dash</strong></summary>
672
673 The field under this rule may have alpha-numeric characters, as well as dashes and underscores.
674
675 </details>
676
677 <details><summary><strong>alpha_spaces</strong></summary>
678
679 The field under this rule may have alpha characters, as well as spaces.
680
681 </details>
682
683 <details><summary><strong>in</strong>:value_1,value_2,...</summary>
684
685 The field under this rule must be included in the given list of values.
686
687 This rule is using `in_array` to check the value.
688 By default `in_array` disable strict checking.
689 So it doesn't check data type.
690 If you want enable strict checking, you can invoke validator like this:
691
692 ```php
693 $validation = $validator->validate($data, [
694 'enabled' => [
695 'required',
696 $validator('in', [true, 1])->strict()
697 ]
698 ]);
699 ```
700
701 Then 'enabled' value should be boolean `true`, or int `1`.
702
703 </details>
704
705 <details><summary><strong>not_in</strong>:value_1,value_2,...</summary>
706
707 The field under this rule must not be included in the given list of values.
708
709 This rule also using `in_array`. You can enable strict checking by invoking validator and call `strict()` like example in rule `in` above.
710
711 </details>
712
713 <details><summary><strong>min</strong>:number</summary>
714
715 The field under this rule must have a size greater or equal than the given number.
716
717 For string value, size corresponds to the number of characters. For integer or float value, size corresponds to its numerical value. For an array, size corresponds to the count of the array. If your value is numeric string, you can put `numeric` rule to treat its size by numeric value instead of number of characters.
718
719 You can also validate uploaded file using this rule to validate minimum size of uploaded file.
720 For example:
721
722 ```php
723 $validation = $validator->validate([
724 'photo' => $_FILES['photo']
725 ], [
726 'photo' => 'required|min:1M'
727 ]);
728 ```
729
730 </details>
731
732 <details><summary><strong>max</strong>:number</summary>
733
734 The field under this rule must have a size lower or equal than the given number.
735 Value size calculated in same way like `min` rule.
736
737 You can also validate uploaded file using this rule to validate maximum size of uploaded file.
738 For example:
739
740 ```php
741 $validation = $validator->validate([
742 'photo' => $_FILES['photo']
743 ], [
744 'photo' => 'required|max:2M'
745 ]);
746 ```
747
748 </details>
749
750 <details><summary><strong>between</strong>:min,max</summary>
751
752 The field under this rule must have a size between min and max params.
753 Value size calculated in same way like `min` and `max` rule.
754
755 You can also validate uploaded file using this rule to validate size of uploaded file.
756 For example:
757
758 ```php
759 $validation = $validator->validate([
760 'photo' => $_FILES['photo']
761 ], [
762 'photo' => 'required|between:1M,2M'
763 ]);
764 ```
765
766 </details>
767
768 <details><summary><strong>digits</strong>:value</summary>
769
770 The field under validation must be numeric and must have an exact length of `value`.
771
772 </details>
773
774 <details><summary><strong>digits_between</strong>:min,max</summary>
775
776 The field under validation must have a length between the given `min` and `max`.
777
778 </details>
779
780 <details><summary><strong>url</strong></summary>
781
782 The field under this rule must be valid url format.
783 By default it check common URL scheme format like `any_scheme://...`.
784 But you can specify URL schemes if you want.
785
786 For example:
787
788 ```php
789 $validation = $validator->validate($inputs, [
790 'random_url' => 'url', // value can be `any_scheme://...`
791 'https_url' => 'url:http', // value must be started with `https://`
792 'http_url' => 'url:http,https', // value must be started with `http://` or `https://`
793 'ftp_url' => 'url:ftp', // value must be started with `ftp://`
794 'custom_url' => 'url:custom', // value must be started with `custom://`
795 'mailto_url' => 'url:mailto', // value must conatin valid mailto URL scheme like `mailto:a@mail.com,b@mail.com`
796 'jdbc_url' => 'url:jdbc', // value must contain valid jdbc URL scheme like `jdbc:mysql://localhost/dbname`
797 ]);
798 ```
799
800 > For common URL scheme and mailto, we combine `FILTER_VALIDATE_URL` to validate URL format and `preg_match` to validate it's scheme.
801 Except for JDBC URL, currently it just check a valid JDBC scheme.
802
803 </details>
804
805 <details><summary><strong>integer</strong></summary>
806 The field under t rule must be integer.
807
808 </details>
809
810 <details><summary><strong>boolean</strong></summary>
811
812 The field under this rule must be boolean. Accepted input are `true`, `false`, `1`, `0`, `"1"`, and `"0"`.
813
814 </details>
815
816 <details><summary><strong>ip</strong></summary>
817
818 The field under this rule must be valid ipv4 or ipv6.
819
820 </details>
821
822 <details><summary><strong>ipv4</strong></summary>
823
824 The field under this rule must be valid ipv4.
825
826 </details>
827
828 <details><summary><strong>ipv6</strong></summary>
829
830 The field under this rule must be valid ipv6.
831
832 </details>
833
834 <details><summary><strong>extension</strong>:extension_a,extension_b,...</summary>
835
836 The field under this rule must end with an extension corresponding to one of those listed.
837
838 This is useful for validating a file type for a given a path or url. The `mimes` rule should be used for validating uploads.
839
840 </details>
841
842 <details><summary><strong>array</strong></summary>
843
844 The field under this rule must be array.
845
846 </details>
847
848 <details><summary><strong>same</strong>:another_field</summary>
849
850 The field value under this rule must be same with `another_field` value.
851
852 </details>
853
854 <details><summary><strong>regex</strong>:/your-regex/</summary>
855
856 The field under this rule must be match with given regex.
857
858 </details>
859
860 <details><summary><strong>date</strong>:format</summary>
861
862 The field under this rule must be valid date format. Parameter `format` is optional, default format is `Y-m-d`.
863
864 </details>
865
866 <details><summary><strong>accepted</strong></summary>
867
868 The field under this rule must be one of `'on'`, `'yes'`, `'1'`, `'true'`, or `true`.
869
870 </details>
871
872 <details><summary><strong>present</strong></summary>
873
874 The field under this rule must be exists, whatever the value is.
875
876 </details>
877
878 <details><summary><strong>different</strong>:another_field</summary>
879
880 Opposite of `same`. The field value under this rule must be different with `another_field` value.
881
882 </details>
883
884 <details><summary><strong>after</strong>:tomorrow</summary>
885
886 Anything that can be parsed by `strtotime` can be passed as a parameter to this rule. Valid examples include :
887 - after:next week
888 - after:2016-12-31
889 - after:2016
890 - after:2016-12-31 09:56:02
891
892 </details>
893
894 <details><summary><strong>before</strong>:yesterday</summary>
895
896 This also works the same way as the [](#afterafter rule](#after](#after). Pass anything that can be parsed by `strtotime`
897
898 </details>
899
900 <details><summary><strong>callback</strong></summary>
901
902 You can use this rule to define your own validation rule.
903 This rule can't be registered using string pipe.
904 To use this rule, you should put Closure inside array of rules.
905
906 For example:
907
908 ```php
909 $validation = $validator->validate($_POST, [
910 'even_number' => [
911 'required',
912 function ($value) {
913 // false = invalid
914 return (is_numeric($value) AND $value % 2 === 0);
915 }
916 ]
917 ]);
918 ```
919
920 You can set invalid message by returning a string.
921 For example, example above would be:
922
923 ```php
924 $validation = $validator->validate($_POST, [
925 'even_number' => [
926 'required',
927 function ($value) {
928 if (!is_numeric($value)) {
929 return ":attribute must be numeric.";
930 }
931 if ($value % 2 !== 0) {
932 return ":attribute is not even number.";
933 }
934 // you can return true or don't return anything if value is valid
935 }
936 ]
937 ]);
938 ```
939
940 > Note: `Rakit\Validation\Rules\Callback` instance is binded into your Closure.
941 So you can access rule properties and methods using `$this`.
942
943 </details>
944
945 <details><summary><strong>nullable</strong></summary>
946
947 Field under this rule may be empty.
948
949 </details>
950
951 ## Register/Override Rule
952
953 Another way to use custom validation rule is to create a class extending `Rakit\Validation\Rule`.
954 Then register it using `setValidator` or `addValidator`.
955
956 For example, you want to create `unique` validator that check field availability from database.
957
958 First, lets create `UniqueRule` class:
959
960 ```php
961 <?php
962
963 use Rakit\Validation\Rule;
964
965 class UniqueRule extends Rule
966 {
967 protected $message = ":attribute :value has been used";
968
969 protected $fillableParams = ['table', 'column', 'except'];
970
971 protected $pdo;
972
973 public function __construct(PDO $pdo)
974 {
975 $this->pdo = $pdo;
976 }
977
978 public function check($value): bool
979 {
980 // make sure required parameters exists
981 $this->requireParameters(['table', 'column']);
982
983 // getting parameters
984 $column = $this->parameter('column');
985 $table = $this->parameter('table');
986 $except = $this->parameter('except');
987
988 if ($except AND $except == $value) {
989 return true;
990 }
991
992 // do query
993 $stmt = $this->pdo->prepare("select count(*) as count from `{$table}` where `{$column}` = :value");
994 $stmt->bindParam(':value', $value);
995 $stmt->execute();
996 $data = $stmt->fetch(PDO::FETCH_ASSOC);
997
998 // true for valid, false for invalid
999 return intval($data['count']) === 0;
1000 }
1001 }
1002
1003 ```
1004
1005 Then you need to register `UniqueRule` instance into validator like this:
1006
1007 ```php
1008 use Rakit\Validation\Validator;
1009
1010 $validator = new Validator;
1011
1012 $validator->addValidator('unique', new UniqueRule($pdo));
1013 ```
1014
1015 Now you can use it like this:
1016
1017 ```php
1018 $validation = $validator->validate($_POST, [
1019 'email' => 'email|unique:users,email,exception@mail.com'
1020 ]);
1021 ```
1022
1023 In `UniqueRule` above, property `$message` is used for default invalid message. And property `$fillable_params` is used for `fillParameters` method (defined in `Rakit\Validation\Rule` class). By default `fillParameters` will fill parameters listed in `$fillable_params`. For example `unique:users,email,exception@mail.com` in example above, will set:
1024
1025 ```php
1026 $params['table'] = 'users';
1027 $params['column'] = 'email';
1028 $params['except'] = 'exception@mail.com';
1029 ```
1030
1031 > If you want your custom rule accept parameter list like `in`,`not_in`, or `uploaded_file` rules,
1032 you just need to override `fillParameters(array $params)` method in your custom rule class.
1033
1034 Note that `unique` rule that we created above also can be used like this:
1035
1036 ```php
1037 $validation = $validator->validate($_POST, [
1038 'email' => [
1039 'required', 'email',
1040 $validator('unique', 'users', 'email')->message('Custom message')
1041 ]
1042 ]);
1043 ```
1044
1045 So you can improve `UniqueRule` class above by adding some methods that returning its own instance like this:
1046
1047 ```php
1048 <?php
1049
1050 use Rakit\Validation\Rule;
1051
1052 class UniqueRule extends Rule
1053 {
1054 ...
1055
1056 public function table($table)
1057 {
1058 $this->params['table'] = $table;
1059 return $this;
1060 }
1061
1062 public function column($column)
1063 {
1064 $this->params['column'] = $column;
1065 return $this;
1066 }
1067
1068 public function except($value)
1069 {
1070 $this->params['except'] = $value;
1071 return $this;
1072 }
1073
1074 ...
1075 }
1076
1077 ```
1078
1079 Then you can use it in more funky way like this:
1080
1081 ```php
1082 $validation = $validator->validate($_POST, [
1083 'email' => [
1084 'required', 'email',
1085 $validator('unique')->table('users')->column('email')->except('exception@mail.com')->message('Custom message')
1086 ]
1087 ]);
1088 ```
1089
1090 #### Implicit Rule
1091
1092 Implicit rule is a rule that if it's invalid, then next rules will be ignored. For example if attribute didn't pass `required*` rules, mostly it's next rules will also be invalids. So to prevent our next rules messages to get collected, we make `required*` rules to be implicit.
1093
1094 To make your custom rule implicit, you can make `$implicit` property value to be `true`. For example:
1095
1096 ```php
1097 <?php
1098
1099 use Rakit\Validation\Rule;
1100
1101 class YourCustomRule extends Rule
1102 {
1103
1104 protected $implicit = true;
1105
1106 }
1107 ```
1108
1109 #### Modify Value
1110
1111 In some case, you may want your custom rule to be able to modify it's attribute value like our `default/defaults` rule. So in current and next rules checks, your modified value will be used.
1112
1113 To do this, you should implements `Rakit\Validation\Rules\Interfaces\ModifyValue` and create method `modifyValue($value)` to your custom rule class.
1114
1115 For example:
1116
1117 ```php
1118 <?php
1119
1120 use Rakit\Validation\Rule;
1121 use Rakit\Validation\Rules\Interfaces\ModifyValue;
1122
1123 class YourCustomRule extends Rule implements ModifyValue
1124 {
1125 ...
1126
1127 public function modifyValue($value)
1128 {
1129 // Do something with $value
1130
1131 return $value;
1132 }
1133
1134 ...
1135 }
1136 ```
1137
1138 #### Before Validation Hook
1139
1140 You may want to do some preparation before validation running. For example our `uploaded_file` rule will resolves attribute value that come from `$_FILES` (undesirable) array structure to be well-organized array structure, so we can validate multiple file upload just like validating other data.
1141
1142 To do this, you should implements `Rakit\Validation\Rules\Interfaces\BeforeValidate` and create method `beforeValidate()` to your custom rule class.
1143
1144 For example:
1145
1146 ```php
1147 <?php
1148
1149 use Rakit\Validation\Rule;
1150 use Rakit\Validation\Rules\Interfaces\BeforeValidate;
1151
1152 class YourCustomRule extends Rule implements BeforeValidate
1153 {
1154 ...
1155
1156 public function beforeValidate()
1157 {
1158 $attribute = $this->getAttribute(); // Rakit\Validation\Attribute instance
1159 $validation = $this->validation; // Rakit\Validation\Validation instance
1160
1161 // Do something with $attribute and $validation
1162 // For example change attribute value
1163 $validation->setValue($attribute->getKey(), "your custom value");
1164 }
1165
1166 ...
1167 }
1168 ```
1169