首页 > 解决方案 > 必填字段的前端验证,以单选按钮的值为条件

问题描述

我有一个 Laravel Blade 表单,我在其中填写了如下所需的字段:

<input id="name" type="text" class="form-control @error('name') is-invalid @enderror" name="name" value="{{ old('name') }}" required autocomplete="name" autofocus>

                            @error('name')
                                <span class="invalid-feedback" role="alert">
                                    <strong>{{ $message }}</strong>
                                </span>
                            @enderror

这有效,当我尝试提交没有name值的表单时,我收到此错误:

在此处输入图像描述

但是,现在我有一个单选按钮和另一个名为postal_code

<input type="radio" name="billing_type" class="billing_type" value="paypal" checked /> PayPal
<input type="radio" name="billing_type" class="billing_type" value="card" /> Credit Card

<input type="text" class="form-control" name="postal_code" value="{{ old('postal_code') }}" placeholder="" />

如何使该postal_code字段成为必填项,但前提是单选按钮设置为 value card

我可以在后端处理验证,但我想要刀片中的前端验证,就像我对name上面的字段一样。

标签: laravellaravel-blade

解决方案


您可以使用 jquery 制作,如果值为卡片,则添加所需的属性。否则,将其删除。

$('.billing_type').change(function() {
    var type = $(this).val();
    if(type == 'card'){
        $('.postal_code').attr("required","required");
    }else{
        $('.postal_code').removeAttr("required");
    }
});

推荐阅读