Front-end 对必填字段的验证,以单选按钮的值为条件

Front-end validation for required field, conditional to value of radio button

我有一个 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 字段成为必填字段,但前提是单选按钮设置为值 card

我可以在 back-end 中处理验证,但我想要在 blade 中进行 front-end 验证,就像我在上面的 name 字段中所做的那样。

你可以用jquery来实现,如果值为卡片,则添加一个必需的属性。否则,删除它。

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