Skip to content

Validation

Bag uses Laravel's validation system to validate input data. You can define validation rules using annotations, and/or using the rules() method.

Bag will automatically validate input data when creating a new instance using the Bag::from() method.

php
use Bag\Attributes\Validation\Required;
use Bag\Bag;

readonly class MyValue extends Bag
{
    public function __construct(
        #[Required]
        public string $name,
        public int $age,
    ) {
    }

    public static function rules(): array
    {
        return [
            'name' => ['string'],
            'age' => ['integer'],
        ];
    }
}

In this example we added a #[Required] attribute to the name property, and defined validation rules in the rules() method.

You can validate a Bag object using the Bag::validate() method:

php
$value = MyValue::validate([
    'name' => 'Davey Shafik',
    'age' => 40,
]);

Built-in Validation Attributes

Bag provides a number of built-in validation attributes, based on various Laravel validation rules:

RuleUsage
BetweenThe value should be between two values (inclusive)#[Between(1, 10)]
BooleanThe value should be a boolean#[Boolean]
DecimalThe value should be a decimal number#[Decimal]
EmailThe value should be an email address#[Email]
EnumThe value should be an enum case#[Enum(MyEnum::class)]
InThe value should be in the given list#[In('foo', 'bar')]
IntegerThe value should be an integer#[Integer]
MaxThe value should be at most a given size#[Max(100)]
MinThe value should be at minimum a given size#[Min(1)]
NotRegexThe value should not match a given regex#[NotRegex('/regex/')]
NumericThe value should be numeric#[Numeric]
RegexThe value should match a given regex#[Regex('/regex/')]
RequiredThe value is required#[Required]
RequiredIfThe value is required if another field matches a value#[RequiredIf('otherField', 'value')]
RequiredUnlessThe value is required unless another field matches a value#[RequiredUnless('otherField', 'value')]
RequiredWithThe value is required if another field is present#[RequiredWith('otherField')]
RequiredWithAllThe value is required if more than one other field is present#[RequiredWithAll('otherField', 'anotherOtherField')]
SizeThe value should have a specific size#[Size(10)]
StrThe value should be a string#[Str]

In addition, a generic \Bag\Attributes\Validation\Rule attribute is available to apply any Laravel validation rule:

php
use Bag\Attributes\Validation\Rule;

readonly class MyValue extends Bag
{
    public function __construct(
        #[Required]
        public string $username,
        public string $password,
        #[Rule('same:password')]
        public string $passwordConfirmation,
    ) {
    }
}

Made with 🦁💖🏳️‍🌈 by Davey Shafik.