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

如何用JavaScript的endsWith实现表单验证:输入需以'City'结尾

JavaScript表单验证:确保输入内容以'City'结尾

嘿,这个需求其实挺容易实现的,我给你分享几种实用的方案,从简单的判断逻辑到完整的表单集成都有,你可以根据自己的场景选:

方法1:用ES6的endsWith()方法(最直观)

endsWith()是字符串原生方法,专门用来判断字符串是否以指定后缀结尾,代码写起来特别简洁:

// 获取输入框的值
const inputValue = document.getElementById('cityInput').value;

// 基础判断(严格区分大小写)
if (inputValue.endsWith('City')) {
  console.log('验证通过!');
} else {
  console.log('输入必须以"City"结尾哦!');
}

如果需要忽略大小写(比如用户输入"city"或者"CITY"也能通过),可以先把输入值转成统一大小写再判断:

const normalizedValue = inputValue.trim().toLowerCase(); // 先去掉首尾空格再转小写
if (normalizedValue.endsWith('city')) {
  console.log('验证通过!');
} else {
  console.log('输入必须以"City"(不区分大小写)结尾哦!');
}

方法2:用正则表达式(更灵活)

如果你需要更复杂的匹配规则,正则表达式是更好的选择。比如下面的正则可以匹配任意以'City'结尾的字符串,还支持忽略大小写:

const inputValue = document.getElementById('cityInput').value.trim();
const cityRegex = /^.*City$/i; // i表示忽略大小写,^.*匹配开头任意字符,$表示结尾

if (cityRegex.test(inputValue)) {
  console.log('验证通过!');
} else {
  alert('输入内容必须以"City"结尾,请检查!');
}

方法3:完整的表单提交验证示例

下面是一个完整的表单集成案例,当用户提交表单时自动触发验证,不通过就阻止提交并提示错误:

<form id="cityForm">
  <label for="cityInput">城市名称:</label>
  <input type="text" id="cityInput" name="city" required>
  <button type="submit">提交</button>
  <p id="errorMsg" style="color: red; display: none;"></p>
</form>

<script>
const form = document.getElementById('cityForm');
const errorMsg = document.getElementById('errorMsg');

form.addEventListener('submit', function(e) {
  e.preventDefault(); // 先阻止默认提交行为
  const inputValue = document.getElementById('cityInput').value.trim();
  
  // 验证逻辑
  if (inputValue.endsWith('City')) {
    errorMsg.style.display = 'none';
    alert('验证通过,表单即将提交!');
    // form.submit(); // 验证通过后手动提交表单
  } else {
    errorMsg.textContent = '输入必须以"City"结尾,请修正!';
    errorMsg.style.display = 'block';
  }
});
</script>

额外小贴士

  • 记得用trim()处理输入值,避免用户输入首尾空格导致验证失败(比如" ShanghaiCity "这种情况)
  • 如果需要支持旧浏览器(不支持endsWith()),可以用正则表达式替代,或者自己封装一个兼容方法

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:20:02