Guide

Validation

Validation schemas, one-time input validation, and reusable logic in a dedicated service.

Build a validation schema

Use ValidationSchema::create() when the schema should be explicit or reusable. Prefer small built-in rules.

example.php
use Lemonade\Framework\Validation\ValidationSchema;

$schema = ValidationSchema::create()
    ->field('title', 'Title')
        ->required()
        ->maxLength(120)
    ->end()
    ->field('published', 'Published')
        ->required()
        ->inList(['0', '1'])
    ->end();

Run validation once

Build the payload first, validate it once, and then branch on isValid(). The result exposes errors(), failedRules(), and validated().

example.php
$payload = [
    'title' => $this->inputString('title'),
    'published' => $this->inputString('published', '0'),
];

$result = $this->validator()->validate($payload, $schema);

if (!$result->isValid()) {
    return $this->html(
        $this->view()->template('layouts.app', 'pages.article-form', [
            'errors' => $result->errors(),
            'values' => $payload,
        ]),
        422,
    );
}

Move repeated validation into a service

When the same validation logic repeats, move it into an application validation service. The skeleton demonstrates this approach on the contact form.

example.php
<?php

declare(strict_types=1);

namespace App\Validation;

use Lemonade\Framework\Validation\FormValidation;
use Lemonade\Framework\Validation\ValidationResult;

final class ArticleValidator
{
    public function __construct(
        private readonly FormValidation $validator,
    ) {}

    /**
     * @param array<string, mixed> $data
     */
    public function validate(array $data): ValidationResult
    {
        return $this->validator
            ->field('title', 'Title')
                ->required()
                ->maxLength(120)
            ->validate($data);
    }
}