You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用jQuery结合Bootstrap根据验证API返回的JSON动态添加错误提示div?

实现动态添加Bootstrap验证错误提示框的方案

当然可以实现!结合jQuery和Bootstrap的特性,我们完全能搞定这个动态添加错误提示框的需求,而且实现起来很简洁。下面是具体的实现思路和代码示例:

1. 准备API返回的错误数据

假设你已经通过AJAX请求拿到了验证API的JSON响应,我们先把它存到变量里:

const validationErrors = {"backgroundcolor": "Color is not Supported", "terms" : "Sorry the Terms are blank"};

2. 遍历错误并动态插入提示框

利用jQuery的遍历方法,我们可以逐个处理每个字段的错误信息,找到对应输入框后追加提示元素:

// 遍历所有错误项
$.each(validationErrors, function(fieldId, errorMessage) {
  // 定位到对应ID的输入字段
  const $targetInput = $('#' + fieldId);
  
  // 先移除已存在的旧提示框,避免重复添加
  $targetInput.next('.invalid-feedback').remove();
  
  // 给输入框加上Bootstrap的is-invalid类,触发错误样式
  $targetInput.addClass('is-invalid');
  
  // 构建提示框元素,注意ID命名避免和输入框冲突
  const feedbackElement = $('<div>', {
    id: `${fieldId}FeedBack`,
    class: 'invalid-feedback',
    text: errorMessage
  });
  
  // 把提示框插入到输入框的后面
  $targetInput.after(feedbackElement);
});

关键细节说明

  • 防止重复提示:每次添加新提示前先移除输入框后方已有的.invalid-feedback元素,避免多次提交后出现重复的错误提示。
  • Bootstrap样式兼容:必须给输入框添加is-invalid类,这样Bootstrap才会显示对应的红色错误边框和提示框样式。
  • 唯一ID规则:提示框的ID采用原字段ID + FeedBack的格式,既符合你给出的示例要求,又不会和输入框的ID产生冲突。

效果示例

以backgroundcolor字段为例,执行代码前后的HTML结构变化如下:

添加前的结构:

<div class="col-md-6">
  <input type="text" class="form-control" id="backgroundcolor" aria-describedby="validationServer03Feedback" required>
</div>

添加后的结构:

<div class="col-md-6">
  <input type="text" class="form-control is-invalid" id="backgroundcolor" aria-describedby="validationServer03Feedback" required>
  <div id="backgroundcolorFeedBack" class="invalid-feedback"> Color is not Supported </div>
</div>

内容的提问来源于stack exchange,提问作者Mohit H

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 22:43:13