Skip to content

Commit 3ad71fb

Browse files
committed
Add documentation for callback rule
1 parent 1e5a33a commit 3ad71fb

File tree

1 file changed

+47
-2
lines changed

1 file changed

+47
-2
lines changed

README.md

Lines changed: 47 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -293,6 +293,7 @@ Below is list of all available validation rules
293293
* [different](#rule-different)
294294
* [after](#after)
295295
* [before](#before)
296+
* [callback](#callback)
296297

297298
<a id="rule-required"></a>
298299
#### required
@@ -489,10 +490,54 @@ Anything that can be parsed by `strtotime` can be passed as a parameter to this
489490

490491
This also works the same way as the [after rule](#after). Pass anything that can be parsed by `strtotime`
491492

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+
492537
## Register/Modify Rule
493538

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`.
496541

497542
For example, you want to create `unique` validator that check field availability from database.
498543

0 commit comments

Comments
 (0)