Home > Mobile >  Disallow @ character in html5 input field
Disallow @ character in html5 input field

Time:12-31

we have been using html5 field validation like this successfully:

<input type="text" title="This field is required" required>

But for a specific field, we like to disallow specific special character: @ in the field. We tried using pattern, but its not working. The code is as given below

<input type="text" pattern="[^@]" title="Do not allow @" title="This field is required" required>

Any idea on how to do this right. By the way wishing all of you happy new year and hope we don't get to face any coding issues in the new year !

CodePudding user response:

If you want to disable user to write @ character use this code

<!DOCTYPE html>
<html>
<body>
  <form id="my-form">
    <input type="text" id="myInputID">
    <button type="submit" onclick="submit()">Submit</button>
  </form>

  <script>
    var el = document.getElementById("myInputID");
    el.addEventListener("keypress", function(event) {
      if (event.key === '@') {
        event.preventDefault();
      }
    });

  </script>
</body>
</html>

CodePudding user response:

You can disallow the @ char on submit if you add after [^@] in the pattern attribute value:

<form>
<input type="text" pattern="[^@] " title="Do not allow @" title="This field is required" required />
<input type="Submit"/>
</form>

The pattern="[^@] " pattern translates into ^(?:[^@] )$ that matches one or more chars other than @ from start till end.

However, if you want to also block the @ char input, you can enhance the above code to

<form>
  <input type="text" pattern="[^@] " onkeypress="return event.charCode !== 64" title="Do not allow @" title="This field is required" required />
  <input type="Submit" />
</form>

This will still allow to paste @ in the input field form though.

  • Related