Laravel Validation If checkbox ticked then Input text is required?

邮差的信 提交于 2020-01-01 11:37:51

问题


I have been reading Laravel validation documentation. I am not clear how to combine two rules.

For example:

<input type="checkbox" name="has_login" value="1">

<input type="text" name="pin" value="">

If has_login checkbox is ticked then Input text pin value is required.

If has_login is not ticked then Input text pin is not required.

Laravel Validation:

public function rules()
{
    return [
          'has_login' => 'accepted',
          'pin' => 'required',
    ];
}

回答1:


Use required_with or required_if

required_with:foo,bar

The field under validation must be present and not empty only if any of the other specified fields are present.

return [
      'has_login' => 'sometimes',
      'pin'       => 'required_with:has_login,on',
];

--

required_if:anotherfield,value

The field under validation must be present and not empty if the anotherfield field is equal to any value.

return [
      'has_login' => 'sometimes',
      'pin'       => 'required_if:has_login,on',
];

--

https://laravel.com/docs/5.2/validation

--

Also, if the checkbox has_login is not checked, it will not send as part of the form submission



来源:https://stackoverflow.com/questions/38525613/laravel-validation-if-checkbox-ticked-then-input-text-is-required

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!