Hello,
I have an HTML textarea element. I want to prevent a user from entering any HTML tags in this area. How do I detect if a user has entered any HTML a textarea with JavaScript?
Thank you
Hello,
I have an HTML textarea element. I want to prevent a user from entering any HTML tags in this area. How do I detect if a user has entered any HTML a textarea with JavaScript?
Thank you
firstly, bear in mind that you'll need to re-validate on the server side, since anyone can fake a http post, and if they have javascript disabled then of course you have no control :)
what i'd do is
<textarea onkeypress="disableHtml(this);" name="text"></textarea>
and for the javascript
function disableHtml(element) {
element.value = element.value.replace(/[<>]/g, '');
}
another way to do this would be to replace < and > with < and > on the server side, which is the better way because it's secure and people can still frown >:)
[edit : you can make the regexp as clever as you like, if you want to only detect certain tags for instance]
One of the ways is to let the keypress
event return false
when the pressed key matches <
or >
. To distinguish real HTML tags from innocent "lesser than" and "greater than" signs, you may need to put some regex in. And since you can't parse HTML reliably with regex... There's however a jQuery way:
var sanitized = $('<div>').html(textareavalue).text();
The normal practice is however to just let the client enter whatever it want and sanitize HTML during display by the server side view technology in question. How to do it depends on the view technology you're using. In for example PHP you can use htmlspecialchars()
for this and in JSP/JSTL the fn:escapeXml()
. This is more robust since Javascript can be disabled/hacked/spoofed by the client.
You can use a regular expression, like
if ( textArea.value.match(/<\/*[a-z][^>]+?>/gi) ) {
// do something about it
}
where "textArea" is the ID of your textarea
element.
What can you consider as HTML tags? Is <b>
a tag? What about the middle characters in I <3 how 5 is > 4
?
I think you should not limit users with your strictness. Don't be a Steve Jobs.