Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
71
rated 0 times [  74] [ 3]  / answers: 1 / hits: 17787  / 4 Years ago, sun, june 21, 2020, 12:00:00

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


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:


output1


More From » html

 Answers
81

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>




[#50862] Sunday, June 7, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
gavenmekhio

Total Points: 732
Total Questions: 89
Total Answers: 93

Location: Central African Republic
Member since Mon, Aug 10, 2020
4 Years ago
;