DLight\Application\Validator

Mô tả: validate dữ liệu theo rule string kiểu required|email|min:8 và hỗ trợ rule cho upload file. Sau khi make(), bạn đọc kết quả bằng fails(), errors(), first().

Namespace / đăng ký

  • Namespace: DLight\Application
  • File: src/Application/Validator.php

Public API (hay dùng)

  • $v->make(array $data, array $rules, array $messages = []): void
  • $v->fails(): bool
  • $v->errors(): array
  • $v->first(): ?string

Ngoài ra có các helper static: required, email, minLength, maxLength, numeric, integer, boolean, alpha, alphaNum, inList, notInList, date, url, và nhóm file: isFile, isImage, mimes, mimeTypes, maxFile, betweenFile.

Rule hỗ trợ

  • Cơ bản: required, email, string, min:N, max:N, numeric, integer, boolean, alpha, alpha_num, in:a,b, not_in:a,b, date, url, array
  • File: file, image, mimes:jpg,png, mimetypes:image/jpeg,image/png, max:1024 (KB), between:100,500 (KB)

Demo validate form

use DLight\Application\Validator;
use DLight\Application\Request;

$req = new Request();
$data = $req->all();

$v = new Validator();
$v->make($data, [
    'email' => 'required|email',
    'password' => 'required|min:8|max:64',
], [
    'email.required' => 'Email bắt buộc',
    'email.email' => 'Email không hợp lệ',
]);

if ($v->fails()) {
    // Lấy lỗi đầu tiên
    $first = $v->first();
    // Hoặc toàn bộ lỗi theo field
    $errors = $v->errors();
}

Demo validate upload file

use DLight\Application\Validator;

$data = [
  'avatar' => $_FILES['avatar'] ?? null,
];

$v = new Validator();
$v->make($data, [
  'avatar' => 'file|image|mimes:jpg,png,webp|max:1024',
]);