PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, February 25, 2022

[FIXED] Laravel Validation for integers or specific word

 February 25, 2022     laravel, laravel-5, laravel-validation, php, regex     No comments   

Issue

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?


Solution

$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.



Answered By - Serhii Topolnytskyi
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing