使用Laravel 5.1,是否只有在满足两个条件时才需要字段?
在下面的代码示例中,在规则中,我有field2_en和field2_de。我为每个字段设置了2个required_if规则,如果满足2 OR或者required_if规则中的1个,则该字段变为必需字段。这不是我想要的。这就是我想要的:
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']
];
}
}
我已经能够有时候()像下面这样或者使用扩展,但我想知道是否有其他方法可以做到这一点,因为我使用的是laravel-jsvalidation插件而且它没有使用这种有时有条件的验证。
protected function getValidatorInstance()
{
$validator = parent::getValidatorInstance();
$validator->sometimes('field2_en', 'required|min:2', function($input)
{
return ($input->language == 'en' && $input->radiobutton == '2');
});
...
return $validator;
}