How can I use JavaScript to prevent the user from entering these HTML tags in a text box?
<style></style> <script></script> <embeded></embeded> <img src="" />
, - Javascript: , , ( , ) -side script . , - , GET POST script. javascript. script , . , , , .
Javascript "" , .
onChange, :
onChange
<textarea onchange="javascript:sanitizeHTML(this);>...</textarea>
, sanitizeHTML , (), , .
sanitizeHTML
, HTML-, , onkeyup, .
onkeyup
sanitizeHTML str.replace .
str.replace
function sanitizeHTML(object) { object.value.replace("<embed>.*?</embed>", ""); <etc for other tags> }
. ...
<textarea id="mytext" onChange="stripHTML(this.value);"></textarea>
<script> function stripHTML(oldString) { var result=(/<img.*|<script.*|<style.*|<embeded.*/ig).test(oldString); alert('Input is :'+!result); } </script>
// remove onChange="stripHTML(this.value);" from html and do below <script> $(document).ready(function() { $('#mytext').live ('mouseleave change', function () { var textVal= $(this).val(); var result=(/<img.*|<script.*|<style.*|<embeded.*/ig).test(textVal); alert('input is:'+!result); }); });
One useful link
This may lead you in the right direction. help and this
str=(document.getElementById('exp')).value; if(str.match(/([\<])([^\>]{1,})*([\>])/i)==null) alert("No HTML Tag"); else alert("Contains HTML Tag");
or
var htstring = '<p align="Left"><b>Hello</b> <I>World</I></p>'; var stripped = htstring.replace(/(<([^>]+)>)/ig,""); with (document) { write ('Original string:' + htstring + '<br>'); write ('Stripped string:<br><br>' + stripped); }
I wrote the following answer, which is a generalization of this problem. Just reduce the regex tag list to your own list.
JavaScript - HTML detection