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:
Rule | Usage | |
---|---|---|
Between | The value should be between two values (inclusive) | #[Between(1, 10)] |
Boolean | The value should be a boolean | #[Boolean] |
Decimal | The value should be a decimal number | #[Decimal] |
The value should be an email address | #[Email] | |
Enum | The value should be an enum case | #[Enum(MyEnum::class)] |
In | The value should be in the given list | #[In('foo', 'bar')] |
Integer | The value should be an integer | #[Integer] |
Max | The value should be at most a given size | #[Max(100)] |
Min | The value should be at minimum a given size | #[Min(1)] |
NotRegex | The value should not match a given regex | #[NotRegex('/regex/')] |
Numeric | The value should be numeric | #[Numeric] |
Regex | The value should match a given regex | #[Regex('/regex/')] |
Required | The value is required | #[Required] |
RequiredIf | The value is required if another field matches a value | #[RequiredIf('otherField', 'value')] |
RequiredUnless | The value is required unless another field matches a value | #[RequiredUnless('otherField', 'value')] |
RequiredWith | The value is required if another field is present | #[RequiredWith('otherField')] |
RequiredWithAll | The value is required if more than one other field is present | #[RequiredWithAll('otherField', 'anotherOtherField')] |
Size | The value should have a specific size | #[Size(10)] |
Str | The 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,
) {
}
}