Laravel中如何基于某字段值设置另一字段的最小输入值
实现方案
核心逻辑
- 监听
start输入框的数值变化事件,动态同步修改stop输入框的min属性 - 可额外补充兼容逻辑:如果
stop已有输入值小于新的最小限制,可选择自动清空或修正为合法值,避免提交时出现校验报错
完整可运行代码
我先修正了你原HTML代码中重复的style属性、缺失的闭合标签、label的for属性不匹配问题,再补充联动逻辑:
<div class="mb-3" style="float:left; margin-left: 200px;"> <label for="start" style="width: 7em" class="col-form-label">Start</label> <input type="number" style="width: 7em" name="start" class="form-control" id="start" min="0" required> </div> <div class="mb-3" style="float:left; margin-left: 200px;"> <label for="stop" style="width: 7em" class="col-form-label">Stop</label> <input type="number" style="width: 7em" name="stop" class="form-control" id="stop" min="0" required> </div> <script> const startInput = document.getElementById('start'); const stopInput = document.getElementById('stop'); // 监听start的输入事件,实时同步stop的最小限制 startInput.addEventListener('input', function() { const startVal = Number(this.value); // 仅当输入为合法数字时更新限制 if (!isNaN(startVal)) { stopInput.min = startVal; // 以下为可选兼容逻辑,二选一即可 const currentStop = Number(stopInput.value); if (!isNaN(currentStop) && currentStop < startVal) { // 方案1:清空不符合要求的stop值 stopInput.value = ''; // 方案2:自动把stop值修正为和start一致 // stopInput.value = startVal; } } }) </script>
补充说明
- 原生
number类型输入框会自动根据min属性做基础校验,用户输入小于最小值的内容时,表单提交会触发浏览器默认的错误提示 - 建议后端也要做对应参数校验,避免前端校验被绕过导致异常数据入库
内容的提问来源于stack exchange,提问作者voxire
相关产品推荐
相关产品推荐

