【问题标题】:Front-end validation for required field, conditional to value of radio button必填字段的前端验证,以单选按钮的值为条件
【发布时间】:2020-11-04 11:08:05
【问题描述】:

我有一个 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

我可以在后端处理验证,但我希望在刀片中进行前端验证,就像上面的 name 字段一样。

【问题讨论】:

    标签: laravel laravel-blade


    【解决方案1】:

    你可以用jquery来做,如果值是一张卡片,添加一个需要的属性。否则,删除它。

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

    【讨论】:

      猜你喜欢
      • 2016-04-03
      • 2013-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-18
      • 1970-01-01
      • 2019-03-15
      • 2011-07-07
      相关资源
      最近更新 更多