4

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',
    ];
}

2 Answers 2

9

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']),
        ],
    ];
}
Sign up to request clarification or add additional context in comments.

Comments

0

Please check the Complex Conditional Validation, it's the solution to your request. An example is already given in the documentation however your code block will look like below.

use Illuminate\Support\Facades\Validator;

$validator = Validator::make($request->all(), [
    'type' => 'required',
]);

$validator->sometimes('value', 'required|min:1|max:255|numeric', function ($input) {
    return $input->type == 'numbers';
});

$validator->sometimes('value', 'required|min:1|max:255|alpha', function ($input) {
    return $input->type == 'letters';
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.