Client-side validation

The Loki Components core package offers server-side validation. This is further extended by the Loki Field Components package with client-side validation.

Validation of Field Components

Each Field Component extends from the LokiComponentType object and inherits a value. The goal of Loki Field Components is to standardize the way that Loki Components are working. For instance, via ready-made PHTML templates. All field templates make sure that a AJAX push of the Alpine.js property value occurs via the submit() method and within that submit() method validation is triggered: Validation happens by going through a list of validationActions, one of them being a callback to LokiComponentValidator.validate(this) (explained below).

On top of this, each Field Component has a property validators which contains a flat array of validator names as declared through the etc/loki_components.xml file.

Extending upon the LokiComponentValidator object

The LokiComponentValidator object is declared globally and contains a list of validators (by default, only required) and a validate(component) method. Its goal is to serve as a registry of validators and to be a service for validation.

Adding a new validator (for instance badWords) is done by simply adding a new entry to this list of validators:

<script>
    LokiComponentValidator.validators.badWords = function (component) {
        if (component.value.includes('fart')) {
            component.addLocalError('<?= $escaper->escapeHtml(__('Go wash your mouth')); ?>');
            return false;
        }

        return true;
    }
</script>

The goal is to first write a PHP-based Validator - to guarantee validation occurs at all times, even when JavaScript is disabled by bastards - and then to replicate the PHP-behaviour in JavaScript.

Last modified: September 4, 2025