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

docs: Improve Validation docs #9262

Draft
wants to merge 1 commit into
base: develop
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
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
54 changes: 54 additions & 0 deletions user_guide_src/source/libraries/validation.rst
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,60 @@ Then add validation rules in the controller (**Form.php**):

If you submit the form you should see the success page or the form with error messages.

****************************
Working with different types
****************************

Since the input value is not limited to scalar types, you can check various objects, enumerations or global data (see :ref:`rules-for-file-uploads`).
Working with the validator is no different, you only need to add custom rules.
This behavior can be useful when creating entities.

An example for validation can be ``DateTime`` for the creation date, ``URI`` for the profile link, ``SplFileInfo`` for the avatar file.

Let's check the input data before creating a new user, with a file structure:

.. code-block:: text

app/
├── Config
│ └── Validation.php:
├── Controllers
│ └── UserController.php
├── Entity
│ └── User.php
├── Validation
│ └── UserRules.php
└── ValueObject
└── Name.php

Add custom value-object ``Name``. It is required when working with the ``User``:

.. literalinclude:: validation/048.php
:lines: 2-

Create rule. We want to make sure that the username will be of the specified type and have a non-empty value:

.. literalinclude:: validation/049.php
:lines: 2-

Add rule to list in **app/Config/Validation.php**:

.. literalinclude:: validation/050.php
:lines: 2-

We can check the data manually. It looks more efficiently with the ``Validator``:


.. literalinclude:: validation/051.php
:lines: 2-

.. note:: Additionally, some basic rules can be applied, such as ``required``, ``permit_empty``, ``field_exists``, ``if_exist``.

Try to create a ``User`` in the controller. Depending on the result, we can throw an exception or handle errors:

.. literalinclude:: validation/052.php
:lines: 2-

*********************
Config for Validation
*********************
Expand Down
10 changes: 10 additions & 0 deletions user_guide_src/source/libraries/validation/048.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

namespace App\ValueObject;

class Name
{
public function __construct(public string $value = '')
{
}
}
25 changes: 25 additions & 0 deletions user_guide_src/source/libraries/validation/049.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

namespace App\Validation;

use App\ValueObject\Name;

class UserRules
{
public function valid_name($name, ?string &$error = null)
{
if (! $name instanceof Name) {
$error = 'The name should be Name::class.';

return false;
}

if ($name->value === '') {
$error = 'The name should not be empty.';

return false;
}

return true;
}
}
16 changes: 16 additions & 0 deletions user_guide_src/source/libraries/validation/050.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

namespace Config;

use App\Validation\UserRules;
use CodeIgniter\Config\BaseConfig;

class Validation extends BaseConfig
{
public array $ruleSets = [
// ...
UserRules::class,
];

// ...
}
30 changes: 30 additions & 0 deletions user_guide_src/source/libraries/validation/051.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

namespace App\Entity;

use App\ValueObject\Name;
use DomainException;

class User
{
public Name $name;
public string $createdAt;

public function __construct(array $data = [])
{
if (! service('validation')
->setRules([
'name' => 'required|valid_name',
'created_at' => 'valid_date[d/m/Y]',
])
->run($data)
) {
// The validation failed
throw new DomainException('Invalid data for "User"');
}

// Working with allowed data
$this->name = $data['name'];
$this->createdAt = $data['created_at'];
}
}
29 changes: 29 additions & 0 deletions user_guide_src/source/libraries/validation/052.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

namespace App\Controllers;

use App\Entity\User;
use App\ValueObject\Name;
use DomainException;

class UserController
{
public function index(): string
{
$data = [
'name' => new Name('Ivan'),
'created_at' => '01/01/2000',
];

try {
$user = new User($data);

// Hi, Ivan
return 'Hi, ' . $user->name->value;
} catch (DomainException $e) {
echo 'Found errors: ';

print_r(service('validation')->getErrors());
}
}
}
Loading