0

Here's my code:

$rules = [
    'shape' => ['required', 'in:cubic,rounded'],
    'height' => ['required', 'numeric', 'gt:0'],
    'length' => ['required_if:shape,cubic', 'numeric', 'gt:0'],
    'width' => ['required_if:shape,cubic', 'numeric', 'gt:0'],
    'diameter' => ['required_if:shape,rounded', 'numeric', 'gt:0'],
]

My need is when shape is cubic, validation will ignore diameter (even it gives a value 0). For example: if I post shape=cubic&height=10&length=10&width=10&diameter=0, it will returns The diameter field must be greater than 0.

For diameter field, I want the rules ['numeric', 'gt:0'] only available when shape is rounded, otherwise there should be no rules like [].

I try to use required_if but it's not suit for this case.

Laravel has no rule named if, only required_if or other ..._if rules.

Additional:

Sorry, I didn't make the requirements clear. The fact is that these rules I will use for excel import, so there will be the field diameter anyway

0

3 Answers 3

0

to make your example work just use:

$rules = [
'shape' => ['required', 'in:cubic,rounded'],
'height' => ['required', 'numeric', 'gt:0'],
'length' => ['required_if:shape,cubic', 'numeric', 'gt:0'],
'width' => ['required_if:shape,cubic', 'numeric', 'gt:0'],
'diameter' => ['exclude_if:shape,cubic', 'numeric', 'gt:0'],
]

to add a little bit of context:

The required_if, will validate your input if present that is why your example failed but if it was:

shape=cubic&height=10&length=10&width=10

this would have succeeded.

So if your parameters are always present the exclude_if is what you need

Sign up to request clarification or add additional context in comments.

3 Comments

The truth is that these are the rules I'll be using for the excel import, so there will be a field for diameter anyway
and so exclude_if works well, right?
I haven't used this rule, but I just read the official documentation and it should fit my needs, thank you!
0

You can use the Rule in Laravel

php artisan make:rule

by creating a custom rule you are free to write any kind of validation that you want.

2 Comments

Yes, I know that. I just want to make sure if there's any easier way to do it.
Rules are customized thing, so it need work.
0

You have to use sometimes in validation

$rules = [
    'shape' => ['required', 'in:cubic,rounded'],
    'height' => ['required', 'numeric', 'gt:0'],
    'length' => ['required_if:shape,cubic', 'numeric', 'gt:0'],
    'width' => ['required_if:shape,cubic', 'numeric', 'gt:0'],
    'diameter' => ['sometimes', 'required_if:shape,rounded', 'numeric', 'gt:0'],
];

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.