laravel-strict-validation maintained by joelharkes
Description
Typesafe validation rules for laravel
Author
Last update
2025/02/17 10:02
(dev-main)
License
Downloads
6
Laravel Strict validation 📬
$data = $request->validate(['input' => [new ValidFloat()]);
is_float($data['input']); // true, even when input was "10" string.
If you want to learn how to create reusable PHP packages yourself, take a look at my upcoming PHP Package Development video course.
Installation
You can install the package via composer:
composer require joelharkes/laravel-strict-validation
Usage
$this->validate($request, ['input' => [new ValidFloat()]); // input is always float
$this->validate($request, ['input' => [new ValidCarbon()]); // input is always CARBON
Available Rules:
namespace Joelharkes\LaravelStrictValidation\Rules;
new ValidDatetime();
new ValidDecimal($digits, $decimals);
new ValidFloat();
new ValidIn(['option1', 'option2']); // make sure value is exactly the same as in the given array.
new ValidInteger();
- ValidDatetime
- ValidDate
Make your own rule
Making your own typesafe rule is easy. Just extend the BaseRule and implement the validate method.
Call $this->modifyValue($value) to modify the value.
class YourRule extends \Joelharkes\LaravelStrictValidation\Rules\BaseRule
{
public function validate(string $attribute, mixed $value, \Closure $fail): void
{
if (isNotValid($value)) {
return $fail($attribute, $this->translate('validation.numeric'));
}
// when data is valid, but not in right type:
$this->modifyValue(castToYourType($value));
}
}