Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add validation documentation #132

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 32 additions & 28 deletions docs/extend/validation.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,12 @@ If it fails validation, a `Illuminate\Validation\ValidationException` will be th

Remember that you can turn an Eloquent instance into an associative array of attributes via:

- The `$instance->getAttributes()` method if the instance hasn't been saved.
- The `$instance->getDirty()` method if the instance has been saved.
- `$instance->getAttributes()` will get all attribute values as they are currently present on the model, saved or not
- `$instance->getDirty()` will get all attribute values that have been modified and not yet saved. It works for new or existing models
- `$instance->getChanges()` will get all attributes that were modified and are now saved
- `$instance->getOriginal()` will get all attribute values that were retrieved from the database

Also, keep in mind that it's generally preferable to validate data before pushing it into the model instance.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it would be nice to include a small example here. Maybe:

<?php

use Illuminate\Support\Arr;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;

class MyController implements RequestHandlerInterface
{
    protected $validator;
    public function __construct(UserValidator $validator) {
        $this->validator = $validator;
    }

    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        $attributes = Arr::get($request->getParsedBody(), 'data.attributes', []);

        $this->validator->assertValid($attributes);

        // Do something with the attributes
        // Access them with for example Arr::get($attributes, 'email')
    }
}

Also worth noting somehow:

When validating an array, only keys that are present in the validator will be checked. Other will be left as-it. You should only read values from the array that were validated. To get an array of values that ran through the validator, you can use Arr::only($attributes, array_keys($validator->getRules())).

A validator based on Flarum's AbstractValidator will only validate keys which are present in the $data parameter. This means required rules won't be checked if the data is absent. This is designed to handle API requests where each attribute will be handled separately and ignored when absent. To validate all data including missing data, you need to use a Laravel validator.


We can also create a Laravel validator instance directly by injecting a `Illuminate\Contracts\Validation\Factory` instance. For example:

Expand Down Expand Up @@ -146,33 +150,33 @@ return [
// Register extenders here
(new Extend\Event)->listen(Validating::class, function(Dispatcher $events) {
$events->listen(Validating::class, function(Validating $event) {
// This modification should only apply to UserValidator
if ($event->type instanceof UserValidator) {
$rules = $event->validator->getRules();

// In this case, we are tweaking validation logic for the username attribute,
// so if that key isn't present in rules, there's nothing we need to do.
if (!array_key_exists('username', $rules)) {
return;
}

// Tweak username validation with a custom regex,
// and increase min length to 10 characters.
$rules['username'] = array_map(function(string $rule) {
if (Str::startsWith($rule, 'regex:')) {
return 'regex:/^[.a-z0-9_-]+$/i';
}

if (Str::startsWith($rule, 'min:')) {
return 'min:10';
// This modification should only apply to UserValidator
if ($event->type instanceof UserValidator) {
$rules = $event->validator->getRules();

// In this case, we are tweaking validation logic for the username attribute,
// so if that key isn't present in rules, there's nothing we need to do.
if (!array_key_exists('username', $rules)) {
return;
}

// Tweak username validation with a custom regex,
// and increase min length to 10 characters.
$rules['username'] = array_map(function(string $rule) {
if (Str::startsWith($rule, 'regex:')) {
return 'regex:/^[.a-z0-9_-]+$/i';
}

if (Str::startsWith($rule, 'min:')) {
return 'min:10';
}

return $rule;
}, $rules['username']);

// Update the validator instance with modified rules.
$event->validator->setRules($rules);
}

return $rule;
}, $rules['username']);

// Update the validator instance with modified rules.
$event->validator->setRules($rules);
}
});
}),
];
Expand Down