Skip to Content search facebook instagram pinterest twitter youtube

Validator & Validity classes

The related classes Validator and Validity are used for validating submitted form data. The Validator class provides methods which track which fields have errors, and the Validity class provides static methods for validating input data according to specific rules. Each Validity method throws a ValidationException if the validation fails; and these are handled by the Validator class and put into the session to be displayed with the appropriate fields.

For example:

modules/Example/Controllers/ExampleController.php

// ...
 
public function submitForm()
{
    $_SESSION['example_form'] = [
        'field_values' => Validator::trim($_POST),
    ];
 
    $valid = new Validator($_POST);
    $valid->required(['name', 'email']);
 
    $valid->check('name', 'Validity::length', 1, 100);
    $valid->check('email', 'Validity::length', 1, 100);
    $valid->check('email', 'Validity::email');
    $valid->check('phone', 'Validity::phone');
 
    if ($valid->hasErrors()) {
        $_SESSION['example_form']['field_errors'] = $valid->getFieldErrors();
        $valid->createNotifications();
        Url::redirect('example/form');
    }
 
    $new_person = [
        'name' => $_POST['name'],
        'email' => $_POST['email'],
        'phone' => $_POST['phone'],
    ];
    Pdb::insert('personal_details', $new_person);
 
    Url::redirect('example/success');
}

Custom validation

You can easily create your own class and use it to provide arbitrary field validation, as long as the method throws a ValidationException when required. For example:

modules/Example/Helpers/ValidityExample.php

class ValidityExample
{
    public static function primeToTwenty($val)
    {
        if (!in_array($val, [1, 2, 3, 5, 7, 11, 13, 17])) {
            throw new ValidationException('Must be a prime number between 1 and 20');
        }
    }
}