首页 > 解决方案 > 检测输入字段中的错误信息

问题描述

如果用户键入受限符号,我如何显示消息?

例如,如果用户*在输入字段中键入,则错误消息可能会显示A filename cannot contain any of the following characters: \/:*?"<>|. 我希望有人可以指导我如何做到这一点。谢谢。

<!DOCTYPE html>
<html>
<body>

<h1>How to show error message</h1>


<input type="text" class="form-control blank" id="function_code" name="function_code" title="function_code" onpaste="return false">

</body>
</html>

<script>
document.getElementById("function_code").onkeypress = function(e) {
var chr = String.fromCharCode(e.which);
if ("></\":*?|".indexOf(chr) >= 0)
return false;
};
</script>

如果用户在输入字段中键入限制符号,我的预期结果如下图所示:

输出1

标签: javascripthtmlvalidationinputerror-messaging

解决方案


input事件与正则表达式一起使用,如下所示:

const input = document.getElementById("function_code");
const error = document.getElementById('error');
const regex = /[\\\/:*?"<>|]+/;

input.addEventListener('input', (e) => {
  const value = e.target.value;

  if (regex.test(value)) {
    input.value = value.slice(0, value.length - 1);
    error.textContent = 'A filename cannot contain any of the following characters: \/:*?"<>|';
  } else {
    error.textContent = '';
  }
});
input {
  padding: 8px 10px;
  border-radius: 5px;
  font-size: 1.2rem;
}

#error {
  display: block;
  color: red;
  margin: 5px 0 0 0;
}
<input type="text" id="function_code" name="function_code">
<span id="error"></span>


推荐阅读