Search code examples
javascripthtmlvalidationinputerror-messaging

Detect the error message in the input field


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


Solution

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