IPL: How to use ipl-validator

by | Jun 7, 2023

In my last blogpost I explained how our ipl-html lib works and how to use it.

With the help of ipl-html it is possible to add forms. Usually we want to validate the data of the form before submitting it and display messages if the validation fails. For this purpose, we have introduced the ipl-validator.

The  ipl-validator includes many useful validators, and today I want to explain how you can easily use them.

To demonstrate, we will create a form with two input fields for the username and email address.

<?php

namespace Icinga\Module\Blogpost;

use ipl\Html\Form;
use ipl\Validator\CallbackValidator;
use ipl\Validator\StringLengthValidator;

class BlogpostForm extends Form
{
    protected $defaultAttributes = [
        'id'    => 'blogpost',
        'class' => 'ipl-validator'
    ];

    protected function assemble()
    {
        $this->addElement('input', 'username', [
            'label'         => t('Username'),
            'validators'    => [
                'StringLength' => ['min' => 8],
                'Callback' => function ($value, $validator) {
                    /** @var CallbackValidator $validator */
                    if ($this->db->hasUsername($value)) {
                        $validator->addMessage(t('Username already taken, please use another one'));
                        return false;
                    }

                    return true;
                }
            ]
        ]);

        $this->addElement('input', 'email', [
            'label'         => t('Email'),
            'validators'    => [
                'EmailAddress',
                'Callback' => function ($value, $validator) {
                    /** @var CallbackValidator $validator */
                    if (! str_ends_with($value, '.de')) {
                        $validator->addMessage(t('Only .de emails are allowed'));
                        return false;
                    }

                    return true;
                }
            ]
        ]);
    }

    public function onSuccess()
    {
        // runs when form is valid
        // now you can send data to db or do other stuff
    }
}

 

See how easy it is. We have created a chain of validators for both input fields:

  • Username must be minimum 8 chars long and should not be already existing in the db to pass the validation.
  • Email must be a valid email with @ and end with .de top level domain to pass the validation.

You can also conditionally remove validators or add more as following:

protected function assemble()
{
    ...

    if ($this->db->isPgsql()) {
        $element = $this->getElement('username');
        $element->getValidators()->clearValidators();
        $element->getValidators()->add(new StringLengthValidator(['min' => 4, 'max' => 10]));
    }
}

 

Many of the validators accept additional parameters to validate more strictly.

For a special type of validation, such as a regex match, you can use CallbackValidator and display a custom message if the validation fails.

if ($this->db->isPgsql()) {
    ...

    $element->getValidators()->add(new CallbackValidator(function($value, $validator) {
        if (preg_match('/[^A-Za-z0-9]/', $value)) {
            $validator->addMessage(t('Special chars are not allowed'));

            return false;
        }

        return true;
    }));
}

We are regularly working to make all our ipl libraries even better. Stay tuned for new features and improvements.

You May Also Like…

Releasing Icinga Web v2.12.2

Releasing Icinga Web v2.12.2

Today we’re announcing the general availability of Icinga Web v2.12.2. You can find all issues related to this release...

Subscribe to our Newsletter

A monthly digest of the latest Icinga news, releases, articles and community topics.