0

I want to restrict html input, so user cannot input char # into the input

i tried to use pattern but it seems not working

i add these pattern to my input pattern="[^-#]+"

i expect the user cannot input char #, but it still can, what was wrong?

baycisk
  • 131
  • 2
  • 12
  • This answer should help you. [link to answer](https://stackoverflow.com/a/22708940/3048967) – ScrapCode Apr 26 '19 at 06:17
  • `pattern` won't stop users from typing in those characters. You'd have to use keyup event – adiga Apr 26 '19 at 06:20
  • Possible duplicate of [Restrict characters in input field](https://stackoverflow.com/questions/22708434/restrict-characters-in-input-field) – adiga Apr 26 '19 at 06:21
  • possible duplicate of https://stackoverflow.com/questions/895659/how-do-i-block-or-restrict-special-characters-from-input-fields-with-jquery – Kavvya Ramarathnam Apr 26 '19 at 06:27
  • Possible duplicate of [how do i block or restrict special characters from input fields with jquery?](https://stackoverflow.com/questions/895659/how-do-i-block-or-restrict-special-characters-from-input-fields-with-jquery) – manish kumar Apr 26 '19 at 06:51

3 Answers3

1

Use a key up event and use replace() to replace # with empty string ''.

<script>
function validateInput()
{
   var data = document.getElementById("input").value;
   data = data.replace('#','');
   document.getElementById("input").value = data;
}
</script>
<input type="text" id="input" onkeyup="validateInput()" />
Sudhir Ojha
  • 3,247
  • 3
  • 14
  • 24
0

This worked for me. Place your logic in onkeydown or onkeypress event handler function. find out the charCode. It must be 35. Then simply event.preventDefault() if the condition is met.

dp2050
  • 332
  • 3
  • 8
0

use replace function to replace # with space on keyup or oninput event.

<input type="text" 
oninput="this.value = this.value.replace(/#/g, '')" />
Sunil Kashyap
  • 2,946
  • 2
  • 15
  • 31