Example

Let’s create a login form with a email and a password field. First, we need to create these fields:

use Centum\Forms\Field;

$emailField = new Field("email");

$passwordField = new Field("password");

Centum\Forms\Field implements Centum\Interfaces\Forms\FieldInterface.

Now we need to add some filters and validators to these fields. Obviously, neither of these fields should be empty and the email field should contain a valid email address:

use Centum\Filter\String\Trim;
use Centum\Validator\EmailAddress;
use Centum\Validator\NotEmpty;

$emailField->addFilter(
    new Trim()
);

$emailField->addValidator(
    new NotEmpty()
);

$emailField->addValidator(
    new EmailAddress()
);
use Centum\Validator\NotEmpty;

$passwordField->addValidator(
    new NotEmpty()
);

Filters are applied before validating the data.

Now we need to encapsulate them into a Centum\Forms\Form:

use Centum\Forms\Form;

$loginForm = new Form();

$loginForm->add($emailField);

$loginForm->add($passwordField);

Validating

Validating a Form is done using the validate() method which returns a Centum\Forms\Status object. It has 2 public methods:

  • public function isValid(): bool
  • public function getMessages(): array<string, array<string>>

Centum\Forms\Status implements Centum\Interfaces\Forms\StatusInterface.

Validating data against these filters and validators is as easy as:

$status = $loginForm->validate($_POST);

$success = $status->isValid();

If the data isn’t valid, you can find out why:

$status = $loginForm->validate($_POST);

$errorMessages = $status->getMessages();