在输入字段中检测错误消息 [英] Detect the error message in the input field

查看:105
本文介绍了在输入字段中检测错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I show the message if the user types a restricted symbol?

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

For example, if the user types * in the input field, the error message can show A filename cannot contain any of the following characters: \/:*?"<>|. I hope someone can guide me how to do it. Thanks.

<!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>

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

My expected result is like below the picture if the user types the restrict symbol in the input field:

推荐答案

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

Use the input event along with a regular expression, like so:

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>

这篇关于在输入字段中检测错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆