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

如何为HTML input输入框同时配置两种校验规则?

方案1:直接修改pattern属性(原生HTML校验,无需额外JS)

利用正则负向先行断言,在原有字符校验规则前新增禁用词排除逻辑,无需改动其他原有属性,修改后代码如下:

<input type="text"
    name="firstname"
    id="firstname"
    placeholder="Name"
    maxlength="15"
    pattern="^(?!.*(dog|cat))[a-zA-ZąćęłńóśżźĄĆĘŁŃÓŹŻŚ]+$"
    autofocus
    required >

正则规则说明:

  • (?!.*(dog|cat))是负向先行断言,代表整个字符串中不能出现dog或cat子串,默认区分大小写,如果需要不区分大小写可调整为(?!.*([dD][oO][gG]|[cC][aA][tT]))
  • 后续保留原有字符校验规则,确保仅允许指定的字母输入
  • 如果仅需要禁止独立出现的dog/cat单词,而非包含该字符的其他单词(比如不需要拦截doggy这类词),可将断言调整为(?!.*\b(dog|cat)\b)

方案2:JS自定义校验(适合禁用词较多、需要自定义错误提示的场景)

如果后续禁用词会频繁新增,用JS维护的可扩展性更高,还可以自定义不符合规则时的提示文案,示例代码如下:

<input type="text"
    name="firstname"
    id="firstname"
    placeholder="Name"
    maxlength="15"
    pattern="^[a-zA-ZąćęłńóśżźĄĆĘŁŃÓŹŻŚ]+$"
    autofocus
    required >

<script>
const firstNameInput = document.getElementById('firstname');
// 禁用词可单独维护,后续新增直接往数组里加即可
const forbiddenWords = ['dog', 'cat'];

firstNameInput.addEventListener('input', () => {
  const inputValue = firstNameInput.value;
  const hasForbiddenWord = forbiddenWords.some(word => inputValue.includes(word));
  if (hasForbiddenWord) {
    firstNameInput.setCustomValidity('输入内容不能包含禁用词dog、cat');
  } else {
    // 无禁用词时清空自定义错误,走原生pattern校验逻辑
    firstNameInput.setCustomValidity('');
  }
});
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 17:45:00