Search code examples
laravelvalidationlaravel-validation

Common Rule for Multiple Input Fields pattern in Laravel


I want to create a common rule for multiple Inpute fields with the name pattern "name_*". e.g.

I have multiple input fields with the following names:

  • name
  • name_fruit
  • name_animal
  • name_people
  • name_region
  • name_language
  • description
  • keywords
  • image

And I want fields with pattern name, name_* should be 'required|min:3|max:120' Validator.

Currently, I am using the following rule but it wonly works for the first input field name

    $rules = array(
        'name*'        => 'required|min:3|max:120',
     );

Is there any way using asterisk or regex or other method through which I can?


Solution

  • You're better off just manually returning a rule array with every single one of those keys. It's easier to read.

    public function rules(): array
    {
        return [
            'name'          => 'required|min:3|max:120',
            'name_fruit'    => 'required|min:3|max:120',
            'name_animal'   => 'required|min:3|max:120',
            'name_people'   => 'required|min:3|max:120',
            'name_region'   => 'required|min:3|max:120',
            'name_language' => 'required|min:3|max:120',
            'description'   => '...',
            'keywords'      => '...',
            'image'         => '...',
        ];
    }
    

    Of course, that doesn't mean you can't do what you want. But there is no built in wildcard like that. You'd have to write some extra logic.

    public function rules(): array
    {
        $name_fields = ['name', 'name_fruit', 'name_animal', 'name_people', 'name_region', 'name_language'];
    
        $rules = [];
        foreach ($name_fields as $name_field) {
            $rules[$name_field] = 'required|min:3|max:120';
        }
    
        return $rules + [
            'description'   => '...',
            'keywords'      => '...',
            'image'         => '...',
        ];
    }
    

    Another option is to use array validation. For this to work, you'll need to change the name attribute of your inputs.

    • From name to name_fields[name]
    • From name_fruit to name_fields[fruit]
    • From name_animal to name_fields[animal]
    • From name_people to name_fields[people]
    • From name_region to name_fields[region]
    • From name_language to name_fields[language]
    public function rules(): array
    {
        return [
            'name_fields'   => 'required|array',
            'name_fields.*' => 'required|min:3|max:120',
            'description'   => '...',
            'keywords'      => '...',
            'image'         => '...',
        ];
    }
    

    But this also means there's nothing validating against someone passing in an unkonwn field like say.... name[company] to give an example.