Reputation: 1
I am doing a project in Laravel and adding some validation rule on my form. Here, I have situation where I a field "A" is required if field "B" has specific value. And after field "A" is required then I want to validate value of field "A".
I am trying to do achieve the same using "required_if" validation rule as given below:
['years' => 'required_if:duration_type,0,gt:0'];
Here I want to check if duration type is 0 then my "years" field must be required and value just greater than 0.
Can someone please guide me on how can I achieve the same?
Thanks in Advance
Upvotes: 0
Views: 6462
Reputation: 518
Here it is,
['years' => 'exclude_unless:duration_type,==,0|required|numeric|gt:0'];
exclude_unless
will exclude the rule unless duration_type is 0. When duration_type is 0, years will be required
. And gt
rule should work properly here when it is numeric
.
Upvotes: 0
Reputation: 4271
You can write a DataAwareRule
Rule as laravel's doc explained here.
I wrote a sample rule for you that implemented this interface, and retrieves for example b
parameter and assigns it to b
property of rule object, then you can use it in passes()
method.
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\DataAwareRule;
use Illuminate\Contracts\Validation\Rule;
class ARule implements Rule, DataAwareRule
{
protected $b;
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
if ($this->b == 'specific_value') {
if ($value == 'valid_value') {
return true;
}
}
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return 'The validation error message.';
}
public function setData($data)
{
$this->b = data_get($data, 'b');
}
}
Upvotes: 1
Reputation: 1
https://laravel.com/docs/8.x/validation#conditionally-adding-rules
[years => exclude_unless:duration_type,0,required,gt:0];
Upvotes: 0