Laravel验证如果选中此复选框,则需要输入文本吗? [英] Laravel Validation If checkbox ticked then Input text is required?

查看:96
本文介绍了Laravel验证如果选中此复选框,则需要输入文本吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读Laravel验证文档.我不清楚如何结合两个规则.

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

例如:

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

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

如果选中has_login复选框,则需要输入文本pin值.

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

如果未勾选has_login,则不需要输入文本pin.

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

Laravel验证:

Laravel Validation:

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

推荐答案

使用required_with或required_if

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

如果anotherfield字段等于任何值,则必须存在正在验证的字段,并且该字段不能为空.

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

-

此外,如果未选中复选框has_login,它将不会作为表单提交的一部分发送

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

这篇关于Laravel验证如果选中此复选框,则需要输入文本吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆