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

如何在Web应用中编写函数验证英国邮政编码(UK Postcode)

英国邮政编码验证实现方案(Google Apps Script Web应用)

现有基于Google Apps Script的Web应用运行正常,需要给邮政编码输入框添加英国邮编的实时验证,已准备好验证用的正则表达式,但不清楚如何通过HTML内的函数或代码实现验证逻辑。现有代码片段如下:

现有HTML输入框代码

<div class="cell-6">
 <div class="form-group">
  <label>Post Code</label>
  <input name="postcode" type="text" placeholder="Post Code" class="metro-input"  data-validate="pattern='([a-zA-Z]{1,2}\d{1,2}[a-zA-Z]? ?\d[a-zA-Z]{2}|GIR ?0AA)'">
  </div>  
 </div> 

现有Code.gs核心代码

function doGet() {
  const htmlService = HtmlService.createTemplateFromFile("index")

  htmlService.timestamp = getTimestamp()
  htmlService.courses = getCourses_()
  htmlService.ethnics = getEthnics_()
  htmlService.ages = getAges_()
  htmlService.myunions = getMyUnions_()
  htmlService.pictures = getPictures()
  htmlService.img = getImage()
  const html = htmlService.evaluate().addMetaTag("viewport","width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no")
  return html
}

function acceptData(formData){
console.log(formData)
console.log([formData.firstName])

const ss = SpreadsheetApp.openById("1D4JuWXxTtLqmM9o5pa2pv18NW9qZOIXJXavv777sgpA")
const ws = ss.getSheetByName("Registrations")
ws.appendRow([
  formData.timestamp,
  formData.firstName,
  formData.lastName,
  formData.mobile,
  formData.postcode,
  formData.course,
  formData.accommodation,
  formData.emergencyname,
  formData.emergencynumber,
  formData.healthadjustments,  
  formData.dietary,
  formData.ethnic,
  formData.gender,  
  formData.disabled,
  formData.lgbt,
  formData.myunion,
  formData.hearaboutus,
  formData.fee,
  formData.dataprotection
  ])
}

一、前端实时验证(输入时触发)

直接用原生JavaScript实现输入框的实时校验,给用户即时反馈:

  1. 修改HTML输入框,添加ID和错误提示元素:
<div class="cell-6">
 <div class="form-group">
  <label>Post Code</label>
  <input id="postcodeInput" name="postcode" type="text" placeholder="Post Code" class="metro-input">
  <span id="postcodeError" style="color: red; display: none; font-size: 0.8em;">请输入有效的英国邮政编码</span>
  </div>  
 </div> 
  1. 在HTML的<script>标签中添加验证逻辑:
// 监听输入框输入事件
document.getElementById('postcodeInput').addEventListener('input', function() {
  // 英国邮编正则表达式
  const postcodeRegex = /^([a-zA-Z]{1,2}\d{1,2}[a-zA-Z]? ?\d[a-zA-Z]{2}|GIR ?0AA)$/;
  const inputValue = this.value.trim();
  const errorElement = document.getElementById('postcodeError');

  if (!postcodeRegex.test(inputValue)) {
    errorElement.style.display = 'block';
    this.setCustomValidity('无效的英国邮编格式');
  } else {
    errorElement.style.display = 'none';
    this.setCustomValidity('');
  }
});

// 表单提交前再次校验
document.querySelector('form').addEventListener('submit', function(e) {
  const postcodeInput = document.getElementById('postcodeInput');
  if (!postcodeInput.checkValidity()) {
    e.preventDefault();
    alert('请修正邮政编码格式后再提交');
  }
});

二、后端兜底验证(防止前端绕过)

前端验证可能被篡改,必须在服务器端再加一层校验:

修改Code.gs中的acceptData函数,添加邮编验证逻辑:

function acceptData(formData){
  // 英国邮编正则验证
  const postcodeRegex = /^([a-zA-Z]{1,2}\d{1,2}[a-zA-Z]? ?\d[a-zA-Z]{2}|GIR ?0AA)$/;
  const postcode = formData.postcode.trim();

  // 校验不通过则抛出错误
  if (!postcodeRegex.test(postcode)) {
    throw new Error('无效的英国邮政编码,请检查格式');
  }

  console.log(formData)
  console.log([formData.firstName])

  const ss = SpreadsheetApp.openById("1D4JuWXxTtLqmM9o5pa2pv18NW9qZOIXJXavv777sgpA")
  const ws = ss.getSheetByName("Registrations")
  ws.appendRow([
    formData.timestamp,
    formData.firstName,
    formData.lastName,
    formData.mobile,
    formData.postcode,
    formData.course,
    formData.accommodation,
    formData.emergencyname,
    formData.emergencynumber,
    formData.healthadjustments,  
    formData.dietary,
    formData.ethnic,
    formData.gender,  
    formData.disabled,
    formData.lgbt,
    formData.myunion,
    formData.hearaboutus,
    formData.fee,
    formData.dataprotection
  ])
}

可选:前端处理后端错误提示

如果使用google.script.run提交表单,可添加失败回调展示后端返回的错误:

function submitForm() {
  const form = document.querySelector('form');
  const formData = new FormData(form);

  google.script.run
    .withSuccessHandler(() => {
      alert('提交成功!');
      form.reset();
    })
    .withFailureHandler(error => {
      alert(error.message);
    })
    .acceptData(Object.fromEntries(formData));
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 09:59:51