@@ -293,6 +293,7 @@ Below is list of all available validation rules
293
293
* [ different] ( #rule-different )
294
294
* [ after] ( #after )
295
295
* [ before] ( #before )
296
+ * [ callback] ( #callback )
296
297
297
298
<a id =" rule-required " ></a >
298
299
#### required
@@ -489,10 +490,54 @@ Anything that can be parsed by `strtotime` can be passed as a parameter to this
489
490
490
491
This also works the same way as the [ after rule] ( #after ) . Pass anything that can be parsed by ` strtotime `
491
492
493
+ <a id =" callback " ></a >
494
+ #### callback
495
+
496
+ You can use this rule to define your own validation rule.
497
+ This rule can't be registered using string pipe.
498
+ To use this rule, you should put Closure inside array of rules.
499
+
500
+ For example:
501
+
502
+ ``` php
503
+ $validation = $validator->validate($_POST, [
504
+ 'even_number' => [
505
+ 'required',
506
+ function ($value) {
507
+ // false = invalid
508
+ return (is_numeric($value) AND $value % 2 === 0);
509
+ }
510
+ ]
511
+ ]);
512
+ ```
513
+
514
+ You can set invalid message by returning a string.
515
+ For example, example above would be:
516
+
517
+ ``` php
518
+ $validation = $validator->validate($_POST, [
519
+ 'even_number' => [
520
+ 'required',
521
+ function ($value) {
522
+ if (!is_numeric($value)) {
523
+ return ":attribute must be numeric.";
524
+ }
525
+ if ($value % 2 !== 0) {
526
+ return ":attribute is not even number.";
527
+ }
528
+ // you can return true or don't return anything if value is valid
529
+ }
530
+ ]
531
+ ]);
532
+ ```
533
+
534
+ > Note: ` Rakit\Validation\Rules\Callback ` instance is binded into your Closure.
535
+ So you can access rule properties and methods using ` $this ` .
536
+
492
537
## Register/Modify Rule
493
538
494
- To create your own validation rule, you need to create a class extending ` Rakit\Validation\Rule `
495
- then register it using ` setValidator ` or ` addValidator ` .
539
+ Another way to use custom validation rule is to create a class extending ` Rakit\Validation\Rule ` .
540
+ Then register it using ` setValidator ` or ` addValidator ` .
496
541
497
542
For example, you want to create ` unique ` validator that check field availability from database.
498
543
0 commit comments