javascript - 检测输入字段中的错误信息
问题描述
如果用户键入受限符号,我如何显示消息?
例如,如果用户*
在输入字段中键入,则错误消息可能会显示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>
如果用户在输入字段中键入限制符号,我的预期结果如下图所示:
解决方案
将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>
推荐阅读
- python - 如何按指定的键值对顺序迭代由 JSON 创建的字典?
- excel - 如何输入用户路径并直接分配给命令提示符
- java - Vertx OAuth2AuthHandler 与多个提供商(Facebook、Google 或任何)
- arrays - golang中具有整数和nil值的数组?
- animation - Adobe Animate gotoAndPlay 鼠标滚动
- python - 如何从 MATLAB 中返回的 python 数据类型获取数据?
- python - 使用 CAD 查看器打印预设视图(无需 AutoCAD)
- python - 为 Mac pyodbc 安装 ODBC 驱动程序
- excel - 如何纠正错误“没有为一个或多个参数指定值”
- python - today.strftime('%Y_%m_%d') - 不返回当前日期