I have form that a user can fill-out for selling their home. And for one of the in puts, a user must select weather it will be \"For Sale\" or \"For Rent\". If it is For Sal
There can be another situation when, the requirement will be required if another field is not present, if someone is in this situation, you can do
'your_field.*' => 'required_unless:dependency_field.*,
You could also use the Illuminate\Validation\Rules\RequiredIf
rule directly.
Note: This rule is available in Laravel 5.6 and up.
class SomeRequest extends FormRequest
{
...
public function rules()
{
return [
'sale_price' => new RequiredIf($this->list_type == 'For Sale'),
'rent_price' => new RequiredIf($this->list_type == 'For Rent'),
];
}
}
And if you need to use multiple rules, then you can pass in an array.
public function rules()
{
return [
'sale_price' => [
new RequiredIf($this->list_type == 'For Sale'),
'numeric',
'string',
...
]
];
}
assuming that list_type is the name of the select box to choose from (values : selling or rent)
use it this way
"sale_price" => "required_if:list_type,==,selling"
what does this mean? :
the sale price is only required if the value of list_type is equal to selling
do the same for rent_price
edit
public function rules()
{
return [
'list_type' => 'required',
'sale_price' => 'required_if:list_type,==,For Sale',
'rent_price' => 'required_if:list_type,==,For Rent'
}
You can use Illuminate\Validation\Rule
in Laravel as given below to build the validator.
$validator = Validator::make( $request->input(), [
'list_type' => 'required',
'sale_price'=> Rule::requiredIf( function () use ($request){
return $request->input('list_type') == 'For Sale';
}),
'rent_price'=> Rule::requiredIf( function () use ($request){
return $request->input('list_type') == 'For Rent';
}),
]);