laravel - 必填字段的前端验证,以单选按钮的值为条件
问题描述
我有一个 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
上面的字段一样。
解决方案
您可以使用 jquery 制作,如果值为卡片,则添加所需的属性。否则,将其删除。
$('.billing_type').change(function() {
var type = $(this).val();
if(type == 'card'){
$('.postal_code').attr("required","required");
}else{
$('.postal_code').removeAttr("required");
}
});
推荐阅读
- elasticsearch - 如何在 Elasticsearch 中对同一文档进行最大日期聚合?
- python - Django-Background-Tasks:在午夜初始化任务并在每个午夜重复
- upgrade - 从 umbraco 7.6 升级到 7.15.1 的最佳方法是什么(包括 db 升级)
- java - 如何使用Java检查数据是否写入csv文件?
- r - Plotly R:子图图例和高亮选择之间的交互
- python - Python 聊天机器人“TypeError:'NoneType' 类型的参数不可迭代”
- clojure - reverse vs last 用于查找集合中的最后一个元素
- python - 计算熊猫中的日期差异
- ios - 如何使用操作扩展来抓取网页内容?
- delphi - 在 delphi 上针对 API 28