Skip to content

Commit e128e05

Browse files
committed
Fix #453: Document custom form validation
1 parent ef00df6 commit e128e05

1 file changed

Lines changed: 66 additions & 0 deletions

File tree

src/guide/start/forms.md

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,72 @@ final class Form extends FormModel
4949
In the above example, the `Form` has a single string property `$message` which length should be at least
5050
of two characters. There's also a custom label for the property.
5151

52+
## Custom validation <span id="custom-validation"></span>
53+
54+
Validation attributes are Yii Validator rules. For common checks, first look for an existing rule. For example,
55+
to validate a UUID string, use `Uuid`:
56+
57+
```php
58+
use Yiisoft\FormModel\FormModel;
59+
use Yiisoft\Validator\Rule\Uuid;
60+
61+
final class Form extends FormModel
62+
{
63+
#[Uuid]
64+
public string $id = '';
65+
}
66+
```
67+
68+
When a field needs application-specific validation, use `Callback`. This is useful for one-off checks or for delegating
69+
to a domain/library method. With PHP attributes, use the `method` option because PHP attributes can't contain closures:
70+
71+
```php
72+
<?php
73+
74+
declare(strict_types=1);
75+
76+
namespace App\Web\Echo;
77+
78+
use Yiisoft\FormModel\FormModel;
79+
use Yiisoft\Validator\Label;
80+
use Yiisoft\Validator\Result;
81+
use Yiisoft\Validator\Rule\Callback;
82+
use Yiisoft\Validator\Rule\Required;
83+
use Yiisoft\Validator\Rule\Uuid;
84+
85+
final class Form extends FormModel
86+
{
87+
#[Label('Entity ID')]
88+
#[Required]
89+
#[Uuid(skipOnError: true)]
90+
#[Callback(method: 'validateUuidV7', skipOnError: true)]
91+
public string $id = '';
92+
93+
private function validateUuidV7(mixed $value): Result
94+
{
95+
$isUuidV7 = is_string($value)
96+
&& preg_match(
97+
'/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i',
98+
$value,
99+
) === 1;
100+
101+
if (!$isUuidV7) {
102+
return (new Result())->addError('Entity ID must be a UUID version 7.');
103+
}
104+
105+
return new Result();
106+
}
107+
}
108+
```
109+
110+
The callback method returns a `Result`: return an empty result when the value is valid or add an error when it isn't.
111+
The method body can call any validation code your application already uses, such as
112+
`App\Support\Uuid::isValid($value, 'v7')`.
113+
114+
For validation logic reused in several forms, create a custom Yii Validator rule and handler instead of copying callback
115+
methods. See the [custom rule guide](https://github.com/yiisoft/validator/blob/master/docs/guide/en/creating-custom-rules.md)
116+
for the rule/handler structure.
117+
52118
## Using the form <span id="using-form"></span>
53119

54120
Now that you have a form, use it in your action from "[Saying Hello](hello.md)".

0 commit comments

Comments
 (0)