Using Laravel 5.1, is there a way to require a field ONLY if both conditions are met?
In the code example below, in the rules, I have field2_en and field2_de. I put 2 required_if rules for each field, the field becomes required if 1 of the 2 OR both required_if rules is/are met. It's not what I want. Here is what I want:
- I would like field2_en to be required ONLY if language = en AND radiobutton = 2
- I would like field2_de to be required ONLY if language = de AND radiobutton = 2
AddRequest.php
namespace App\Http\Requests\Post;
use App\Http\Requests\Request;
class AddRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return auth();
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'language' => ['required', 'in:en,de'],
'field1_en' => ['required_if:language,en'],
'field1_de' => ['required_if:language,de'],
'radiobutton' => ['required', 'in:1,2'],
'field2_en' => ['required_if:language,en', 'required_if:radio,2'],
'field2_de' => ['required_if:language,de', 'required_if:radio,2']
];
}
}
I have been able to do it with sometimes() like below or with extend, but I wanted to know if there was other ways of doing it since I am using laravel-jsvalidation plugin and it doesn't work with such sometimes conditional validations.
protected function getValidatorInstance()
{
$validator = parent::getValidatorInstance();
$validator->sometimes('field2_en', 'required|min:2', function($input)
{
return ($input->language == 'en' && $input->radiobutton == '2');
});
...
return $validator;
}
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire