表单字段根据条件进行验证 [英] Form fields Validation on condition

查看:68
本文介绍了表单字段根据条件进行验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果要满足某些条件,我将尝试验证表单上的某些字段.条件是,如果单击复选框,则下面的字段将是必填字段,并且是必填字段;如果不是,则该字段不是必填字段.

I am trying to validate some fields on a form if a certain condition is met, The condition is if a checkbox is clicked then the fields below will be required and mandatory, if not then the fields are not mandatory.

推荐答案

后端验证

您可以使用 required_if Laravel验证规则

You may use required_if Laravel validation rule

$validator = Validator::make($request->all(), [

     'checkbox_field' => 'required|boolean',
     'otherField' => 'required_if:checkbox_field,1',
     // same for other fields

]);

if ($validator->fails()) {
    dd('Validation Error.', $validator->errors());
}

$validatedData = $validator->validated();

前端验证

您还可以使用jQuery添加所需的约束

You may also add required constraints using jQuery

$('#myCheckBoxId').change(function() {

    if($(this).is(':checked')) {
        console.log("Checked");
        $("#myInput1ID").prop('required',true);
        $("#myInput2ID").prop('required',true);
        //...
    } else {
        console.log("Unchecked");
        $("#myInput1ID").removeAttr('required');
        $("#myInput2ID").removeAttr('required');
        //...
    }    

});

检查工作情况演示

这篇关于表单字段根据条件进行验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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