Validation

To validate POST input, create a new class that extends from Core\Helpers\Validator\Validator, and provide validation rules in the constructor.

application/contact/validators/contact.php
<?php

namespace Application\Contact\Validators;

use Core\Helpers\Validator\Validator;

class Page extends Validator
{
    public function __construct()
    {
        $this->validate('firstname', Validator::STRING)->required();
        $this->validate('lastname', Validator::STRING)->required();
        $this->validate('email', Validator::EMAIL)->required();
        $this->validate('message', Validator::STRING)->required();
    }
}

You can then use this class in your controller to validate input. Call the valid() method to check if the input is valid, throw() to throw an exception, and getData() to retrieve the validated input.

application/contact/contact.php
public function post()
{
    $validator = new Validator/Contact();
    
    if (!$validator->valid()) {
        $validator->throw();
    }
    
    $data = $validator->getData();
}

Supported field types

Field type Description
Validator::STRING Input must be a valid string
Validator::INT Input must be a valid integer, or be convertable to an integer.
Validator::EMAIL Input must be a valid email address.
Validator::BOOL Input must be a valid boolean. If not, the field will be converted to `true` if its value is truthy, or `false` if falsy.
Validator::DECIMAL Input must be a valid decimal, or be convertable to a decimal.
Validator::JSON Input must be a JSON formatted string.
Validator::DICT Input must be an associative array.

Available validation methods

required()

Validation must fail if this field is missing.

labeled($label)

Provide a human-readable name for this field, allowing you to call getInvalidFieldLabels() on the validator on failure.

valueIs($value)

Validation must fail if this field does not contain this exact value.

valueBetween(int $lower, int $upper)

Validation must fail if this field does not contain a value within this range.

valueIn(array $array)

Validation must fail if this field does not contain a value from this array.

valueKeyIn(array $array)

Validation must fail if this field does not contain a value corresponding to a key in this associative array.

valueLength(int $min, ?int $max)

Validation must fail if the string length of the value in this field is less than $min (or more than $max if provided).

Edit this page on GitHub Updated at Mon, Feb 14, 2022