joelharkes/laravel-strict-validation

Typesafe validation rules for laravel

0.0.1 2023-04-07 19:51 UTC

This package is auto-updated.

Last update: 2024-10-24 15:41:38 UTC


README

Latest Version on Packagist Build status Total Downloads

$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));
    }
}