Is there Regex to prevent Javascript from being entered?
I have a text a开发者_StackOverflow社区rea which I need to prevent from having javascript entered. If they enter text. And then say some javascript, The javascript runs. And the text does not get entered.
I guess is there a way to stop javascript from being entered in the textfield(say a regex in validation.xml? ) or is there something else I can do from preventing the javascript from being ran at all(maybe on the jsp)!
Here's what I got:
JSP:
<td>
You have <strong><span id="commentsCounter">${const['COMMENT_MAX_LENGTH'] - fn:length(commentForm.comment)}</span></strong> characters left.<br/>
<textarea id="comment" name="comment" rows="2" cols="125" style="width:640px;"
onkeypress="characterCounter('commentsCounter',${const['COMMENT_MAX_LENGTH']}, this)"
onkeydown="characterCounter('commentsCounter',${const['COMMENT_MAX_LENGTH']}, this)"
onkeyup="characterCounter('commentsCounter',${const['COMMENT_MAX_LENGTH']}, this)"></textarea>
<a href="javascript:addComment();"><img src="../images/icon_add.gif" border="0" alt="Add"/></a>
</td>
here is my validation.xml:
<form name="whatif_add_entry_comment">
<field property="id" depends="minlength">
<msg name="minlength" key="ID has a minimum length of {0}" resource="false" />
<arg name="minlength" key="${var:minlength}" resource="false" />
<var>
<var-name>minlength</var-name>
<var-value>0</var-value>
</var>
</field>
<field property="comment" depends="required,minlength,maxlength">
<msg name="required" key="Comment name is required." resource="false" />
<msg name="minlength" key="Comment has minimum length of {0}" resource="false" />
<arg name="minlength" key="${var:minlength}" resource="false" />
<var>
<var-name>minlength</var-name>
<var-value>1</var-value>
</var>
<msg name="maxlength" key="Comment has a maximum length of {0}" resource="false" />
<arg name="maxlength" key="${var:maxlength}" resource="false" />
<var>
<var-name>maxlength</var-name>
<var-value>250</var-value>
</var>
</field>
</form>
You don't need to (and can't easily) escape the javascript itself. You need to escape the HTML. The easiest way is through commons-lang StringEscapeUtils.escapeHtml(..)
(prefer version 3.0)
If you need to retain other html tags, it would be much harder to escape only the javascript. You'd have to look for onclick, onmouseover, etc, etc. For that - take a look at JSoup Cleaner.
If you at all need to support some markup formatting, the usual practice is to allow some limited subset of html or custom tags, like Markdown or BBCode.
精彩评论