Deepak Singh
Deepak Singh

Reputation: 650

Laravel Validation for integers or specific word

I'm creating a validation rule where location attribute can have any integer or a word "all" value.
For integer validation I use this rule:

'location' => 'required|integer'
and for a particular word I can use this rule:

'location' => ['required', Rule::in([all])] 

How can apply both of rules together so that location can either be any integer or the word "all"? Can regex be of any help here?

Upvotes: 3

Views: 4263

Answers (2)

Serhii Topolnytskyi
Serhii Topolnytskyi

Reputation: 820

$this->validate($request, [
    'location' => [
        'required',
        'max:255',
        function ($attribute, $value, $fail) {
            if( is_int( $value ) || 'all' === $value ) {
                return true;
            } else {
                $fail($attribute.' is invalid.');
            }
        },
    ],
]);

But keep in mind: If you send integer via form – you will receive string. And checking is_int( $value ) will not be passed.

Upvotes: 3

revo
revo

Reputation: 48711

You could use a regex rule without required (if you don't mind a separate error message for empty fields):

'location' => ['regex:/^(?:\d+|all)$/']

This means the input value should be either \d or all.

Upvotes: 5

Related Questions