Validation
Glueful currently has two practical validation styles you will encounter:
BaseController::validateRequest()for simple controller-level checks- Rule objects with
Glueful\Validation\Validatorfor more explicit validation flows
Simple Validation In Controllers
If you are using BaseController, this is the shortest path:
public function store(\Symfony\Component\HttpFoundation\Request $request): \Glueful\Http\Response
{
$data = $this->getRequestData();
if ($error = $this->validateRequest($data, [
'email' => 'required|email|max:255',
'name' => 'required|max:100',
])) {
return $error;
}
return $this->created([
'email' => $data['email'],
'name' => $data['name'],
]);
}
This helper is intentionally lightweight. It is good for straightforward endpoint validation.
Rule Object Validation
For stricter or reusable validation, use Validator with rule objects:
use Glueful\Validation\Support\Rules as RuleFactory;
use Glueful\Validation\ValidationException;
use Glueful\Validation\Rules\{
Required,
Email as EmailRule,
Length,
Type,
Range
};
$validator = RuleFactory::of([
'email' => [new Required(), new EmailRule()],
'name' => [new Required(), new Length(2, 100)],
'age' => [new Type('integer'), new Range(18, 120)],
]);
$errors = $validator->validate($input);
if ($errors !== []) {
throw new ValidationException($errors);
}
$data = $validator->filtered();
Type('integer') is strict. It works well for JSON payloads where numeric values are decoded as integers. For form-encoded input, values usually arrive as strings, so use it only when that strictness is what you want.
Useful Built-In Rules
RequiredEmailLengthRangeTypeInArraySanitizeDbUnique
Example: DbUnique
use PDO;
use Glueful\Validation\Rules\DbUnique;
$pdo = new PDO($dsn, $user, $password);
$rules = [
'email' => [
new Required(),
new EmailRule(),
new DbUnique($pdo, 'users', 'email'),
],
];
For direct Validator usage, pass a PDO instance explicitly. Do not assume the validator will inject one automatically.
When To Use Which Style
- Use
validateRequest()for simple app controllers inapi-skeleton - Use rule objects when you need sanitization, custom rules, or more explicit composition
ValidationException Shape
When you throw ValidationException, it carries field errors and is designed to produce a 422 response:
throw new ValidationException([
'email' => ['The email field is required.'],
'name' => ['The name must be at least 2 characters.'],
]);
Recommended Starting Pattern
For most first-party app endpoints, start simple:
$data = $this->getRequestData();
if ($error = $this->validateRequest($data, [
'title' => 'required|max:255',
])) {
return $error;
}
Move to rule objects once the endpoint needs more than basic checks.