ekut/spatie-dto-validators

Set of validators for the package spatie/data-transfer-object

v1.0.1 2022-05-16 04:52 UTC

This package is auto-updated.

Last update: 2024-04-16 08:54:13 UTC


README

Installation

You can install the package via composer:

composer require ekut/spatie-dto-validators
  • Note: This package only supports php:^8.0.

Usage

As you can see in Spatie DTO documentation Validation chapter:

This package doesn't offer any specific validation functionality, 
but it does give you a way to build your own validation attributes. 

So, in this package we just collect set of tested validators for you can easily use it in your projects together with Spatie DTO.

use Ekut\SpatieDtoValidators\MinLength;
use Spatie\DataTransferObject\DataTransferObject;

class Foo extends DataTransferObject
{
    #[MinLength(10)]
    public ?string $property1;
    
    #[GreaterThan(10)]
    public ?int $property2;
}

If any of the validation will be violated, Spatie\DataTransferObject\Exceptions\ValidationException will be thrown with related user-friendly text message.

List of implemented validators

Basic

Blank

    #[Blank()]

Valid values:

  • false (boolean)

  • 0 (int)

  • [] (empty array

  • '' (empty string)

  • "" (empty string)

  • null

  • Note: string '0' is invalid value.

NotBlank

    #[NotBlank(true|false)]

Boolean argument means: is null allowed?

Invalid values:

  • false (boolean)

  • 0 (int)

  • [] (empty array

  • '' (empty string)

  • "" (empty string)

  • null (if null is not allowed by argument)

  • Note: string '0' is valid value.

NotNull

    #[NotNull()]

Only invalid value: null

IsNull

    #[IsNull()]

Only valid value: null

IsTrue

    #[IsTrue()]

Valid values:

  • true (boolean)
  • 1 (int)
  • '1' (string)

IsFalse

    #[IsFalse()]

Valid values:

  • false (boolean)
  • 0 (int)
  • '0' (string)
  • null

Strings

MinLength

    #[MinLength(3)]

Valid: 'car', 'lady', 333, etc.

Invalid: 'on', 'a', 12, 1, etc.

MaxLength

    #[MaxLength(3)]

Valid: 'car', 'on', 'a', 333, 12, 1.

Invalid: 'lady', 'month', 9999, etc.

Email

    #[Email()]

Valid: 'some@fake.com', 'some1@fake.com', 'some_1@fake.com', 'one.more.some@fake.com'.

Invalid: 'fake.com', 'fake@com'.

Url

    #[Url()]

Valid:

Invalid: 'some fake', 'www.example.com', 'example.com'

Comparison

EqualTo

    #[EqualTo(3)]

Valid values: 3, '3'.

NotEqualTo

    #[EqualTo(3)]

Invalid values: 3, '3'.

IdenticalTo

    #[IdenticalTo(3)]

Only valid value: 3.

NotIdenticalTo

    #[NotIdenticalTo(3)]

Only invalid value: 3.

LessThan

    #[LessThan(3)]

LessThanOrEqual

    #[LessThanOrEqual(3)]

GreaterThan

    #[GreaterThan(3)]

GreaterThanOrEqual

    #[GreaterThanOrEqual(3)]

DivisibleBy

    #[DivisibleBy(3)]
    #[DivisibleBy(0.35)]

Choice

Choice

    #[Choice([0, '1', false])]

License

The MIT License (MIT). Please see License File for more information.