I just want ask if how I will block special characters such as <,>,",/,etc. in html input field?
Asked
Active
Viewed 3.1k times
3
-
3By "block" do you mean not allowed to be typed in? What about pasting text? – Spencer Wieczorek Oct 14 '17 at 17:18
-
For what purpose? Are you trying to prevent the user from using HTML? – ceejayoz Oct 15 '17 at 03:34
3 Answers
4
You can explicitly state which characters you accept HTML input pattern Attribute
If you insist on blocking specific characters you can use the following:
document.getElementById("explicit-block-txt").onkeypress = function(e) {
var chr = String.fromCharCode(e.which);
if ("></\"".indexOf(chr) >= 0)
return false;
};
<input type='text' id='explicit-block-txt' value='' onpaste="return false"/>

Dror Moyal
- 398
- 3
- 11
4
You can use regex.
document.getElementById("input").onkeypress = function(e) {
/^[a-zA-Z0-9]+$/.test(this.value) // return true or false
};
<input type="text" id="input">

sametcodes
- 583
- 5
- 8