Search code examples
javascriptjqueryhtmltextareahtmlspecialchars

check whether any html tags entered in textarea using javascript


I'm having a simple commenting system, where i want the user should not type any html special chars, if they done like that they should give an alert of "html tags not allowed". How to do it?

while submitting, a ajax call is passed to another page to store it in db.

So in the javascript itself(before ajax call), how to find is there any html tags in the entered comment.

Any suggestion.


Solution

  • To check you can create an element in the DOM, inject the comment into it and use [element].getElementsByTagName('*') to check for any html element. If its length is not 0, there are html elements in the comment. Something like:

    document.querySelector('#check').addEventListener('click', doCheck);
    
    function doCheck(e) {
     var chkEl = document.createElement('div'), 
         isok,
         report,
         value = document.querySelector('#testing').value;
     if (!value.length) {return true;}
     chkEl.innerHTML = value;
     report = document.querySelector('[data-report]');
     isok = !chkEl.getElementsByTagName('*').length;
     report.setAttribute( 'data-report',
                     !isok 
                     ? 'you can\'t enter html here!' 
                     : 'text looks ok' );
     report.style.color = isok ? 'green' : 'red';
    }
    [data-report]:before {
      content: attr(data-report);
    }
    <textarea id="testing" placeholder="type some stuff"></textarea>
    <span data-report=""></span>
    <br>
    <button id="check">check for html</button>

    Disclaimer: you should always check server side too.