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

Monday, February 14, 2022

[FIXED] Different validation rules for input based on another input value from FormRequest rules() method

 February 14, 2022     laravel, laravel-8     No comments   

Issue

Is it possible to validate an input field conditionally based on the value of another input?

For example, there is an input type which can have the values letters or numbers and then there is another field which contains the value input.

I want that the value input validation rule will be alpha if type is letters and numeric if type is numbers

I am already using the pipe type of validation in the rules method:

public function rules()
{
    return [
        "type" => 'required',
        "value" => 'required|min:1|max:255',
    ];
}

Solution

You can use Rule::when($condition, $rules).

<?php

use Illuminate\Validation\Rule;

public function rules()
{
    return [
        'type' => ['required'],
        'value' => [
            'required',
            'min:1',
            'max:255',
            Rule::when($this->type === 'letters', ['alpha']),
            Rule::when($this->type === 'numbers', ['numeric']),
        ],
    ];
}


Answered By - shabandino
  • 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