4 html javascript validation input error-messaging
如果用户输入受限符号,如何显示消息?
例如,如果用户*
在输入字段中键入内容,则错误消息可能会显示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>
Run Code Online (Sandbox Code Playgroud)
如果用户在输入字段中键入限制符号,我的预期结果如下图所示:
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 = '';
}
});
Run Code Online (Sandbox Code Playgroud)
input {
padding: 8px 10px;
border-radius: 5px;
font-size: 1.2rem;
}
#error {
display: block;
color: red;
margin: 5px 0 0 0;
}
Run Code Online (Sandbox Code Playgroud)
<input type="text" id="function_code" name="function_code">
<span id="error"></span>
Run Code Online (Sandbox Code Playgroud)