joelharkes / laravel-strict-validation
Typesafe validation rules for laravel
0.0.1
2023-04-07 19:51 UTC
Requires
- php: ^8.1
- illuminate/validation: ^10.1
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.14
- phpunit/phpunit: ^9.0
This package is auto-updated.
Last update: 2024-11-24 15:55:48 UTC
README
$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)); } }