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

如何实现表单复选框/单选框必填验证并发送选中值至邮箱?

表单验证逻辑完善方案

问题说明

现有客户工作详情提交表单,包含姓名、邮箱等必填文本项,以及「房产所有权」单选组、「感兴趣的服务」复选组。当前邮件发送功能已实现,但存在验证漏洞:未选择单选框、未勾选任何复选框时,表单仍能提交。需完善验证逻辑,确保只有满足以下条件才允许发送邮件:

  • 所有必填文本项已填写
  • 已选择「房产所有权」单选选项
  • 已勾选至少一项「感兴趣的服务」复选框

修复方案

核心修改点

  1. 补全单选框与复选框的验证逻辑:原代码未对这两组选项做有效验证,添加检查逻辑并给出明确错误提示
  2. 修正按钮状态判断:原按钮仅检查文本项,新增单选/复选框的状态判断,确保按钮仅在所有必填项完成后才激活
  3. 优化服务选择值的获取:避免全局变量重复赋值问题,改用函数返回值方式
  4. 增加容错处理:在邮件组装时对单选框值做容错,防止验证遗漏导致报错

完整代码实现

HTML(新增验证提示元素)

<form id="contact-form">
      <p>Use the form below to send us a message.</p>
          <input  id="form-name" class="form-input" type="text" placeholder="Name" required />
          <input id="form-email" class="form-input" type="text" placeholder="Email" required />
          <input id="form-phone" class="form-input" type="text"  placeholder="Phone" required />
          <input id="form-address" class="form-input" type="text" placeholder="Address" required />
          <input id="form-postcode" class="form-input" type="text" placeholder="Postcode" required />
          <fieldset>
            <h4>Do you own the property?</h4>
            <input type="radio" id="radiooption1" name="form-ownership" value="Yes">
            <label for="radiooption1">Yes</label>
            <br>
            <input type="radio" id="radiooption2" name="form-ownership" value="No">
            <label for="radiooption2">No</label>
          </fieldset>
          <fieldset>
            <h4>What services are you interested in?</h4>
            <input type="checkbox" id="checkoption1" name="form-services" value="Option1">
            <label for="checkoption1"> Option1</label>
            <br>
            <input type="checkbox" id="checkoption2" name="form-services" value="Option2">
            <label for="checkoption2"> Option2</label>
            <br>
            <input type="checkbox" id="checkoption3" name="form-services" value="Option3">
            <label for="checkoption3"> Option3</label>
            <br>
            <input type="checkbox" id="checkoption4" name="form-services" value="Option4">
            <label for="checkoption4"> Option4</label>
            <br>
            <input type="checkbox" id="checkoption5" name="form-services" value="Option5">
            <label for="checkoption5"> Option5</label>
          </fieldset>
      <p id="question"></p>
      <input type="text" class="form-input" id="form-answer">
      <h3 id="submit-btn" onClick="check_form()" >Submit</h3>
      <p id="caution-text" ></p>
      <!-- 新增验证错误提示 -->
      <p id="form-validation-error" style="color: #DB6E24; display: none;"></p>
    </form>

JavaScript(修正验证逻辑)

function check_form() {
  if ($('#form-answer').val() == c) {
    $('#question').html('correct');
    $('#form-answer').css({
      'background-color': '#b5d46c',
      'color': '#fff'
    });
    $('#caution-text').html('');
    $('#form-validation-error').hide();

    form_check();
  } else {
    $('#caution-text').html('Answer incorrect.');
    $('#form-answer').css({
      'background-color': '#DB6E24',
      'color': '#fff'
    });
    $('#form-validation-error').hide();
  }
}

// 监听所有必填项变化,更新按钮状态
$('#form-name, #form-email, #form-phone, #form-address, #form-postcode').change(btn_rdy_check);
$('input[name="form-ownership"], input[name="form-services"]').change(btn_rdy_check);

function btn_rdy_check() {
  const textFieldsFilled = $('#form-name').val() !== "" && 
                           $('#form-email').val() !== "" && 
                           $('#form-phone').val() !== "" && 
                           $('#form-address').val() !== "" && 
                           $('#form-postcode').val() !== "";
  const ownershipSelected = $('input[name="form-ownership"]:checked').length > 0;
  const servicesSelected = $('input[name="form-services"]:checked').length > 0;

  $('#submit-btn').css('background-color', textFieldsFilled && ownershipSelected && servicesSelected ? '#3fd44a' : '#ccc');
}

// 获取选中的服务选项
function getSelectedServices() {
  let selected = "";
  document.getElementsByName('form-services').forEach(checkbox => {
    if (checkbox.checked) selected += `${checkbox.value}, `;
  });
  return selected.length > 0 ? selected.slice(0, -2) : 'No services selected';
}

function form_check() {
  const selectedServices = getSelectedServices();
  const textFieldsFilled = $('#form-name').val() !== "" && 
                           $('#form-email').val() !== "" && 
                           $('#form-phone').val() !== "" && 
                           $('#form-address').val() !== "" && 
                           $('#form-postcode').val() !== "";
  const ownershipSelected = $('input[name="form-ownership"]:checked').length > 0;
  const servicesSelected = $('input[name="form-services"]:checked').length > 0;

  // 收集验证错误
  let errorMsg = "";
  if (!ownershipSelected) errorMsg += "请选择房产所有权状态。<br>";
  if (!servicesSelected) errorMsg += "请至少选择一项感兴趣的服务。<br>";
  if (!textFieldsFilled) errorMsg += "请填写所有必填文本字段。<br>";

  if (errorMsg) {
    $('#form-validation-error').html(errorMsg).show();
    console.log('表单验证未通过');
    return;
  }

  // 验证通过,发送邮件
  send_msg(selectedServices);
}

function send_msg(selectedServices) {
  console.log('开始发送邮件');

  let tmp = "";
  tmp += `<p>Name : ${$('#form-name').val()}</p>`;
  tmp += `<p>Email : ${$('#form-email').val()}</p>`;
  tmp += `<p>Phone : ${$('#form-phone').val()}</p>`;
  tmp += `<p>Address : ${$('#form-address').val()}</p>`;
  tmp += `<p>Postcode : ${$('#form-postcode').val()}</p>`;
  // 容错处理:避免未选中时报错
  const ownershipVal = $('input[name="form-ownership"]:checked').val() || '未选择';
  tmp += `<p>Do you own the property? : ${ownershipVal}</p>`;
  tmp += `<p>What services are you interested in? : ${selectedServices}</p>`;

  const data = {
    details: tmp,
    valid: 'true',
    reply: $('#form-email').val()
  };

  jQuery.post('assets/form/send.php', data, response => {
    console.log(response);
    jQuery('#contact-form').html('<h3>Enquiry sent...</h3>');
  });
}

修复效果

  • 按钮仅在所有必填文本项填写完成、单选框选中、复选框至少选一个时,才会变为绿色激活状态
  • 提交时若验证不通过,会显示明确的错误提示,阻止邮件发送
  • 避免了未选中单选框时组装邮件内容的报错问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 02:07:16