user3784251
user3784251

Reputation: 520

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.

Upvotes: 0

Views: 2195

Answers (3)

LeulAria
LeulAria

Reputation: 605

removing html tags in comment

function sanitizeString(str) {
    str = str.replace(/[^a-z0-9áéíóúñü \.,_-]/gim, " ");    
    return str.trim();
}

Upvotes: 0

KooiInc
KooiInc

Reputation: 122906

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.

Upvotes: 2

Timur Osadchiy
Timur Osadchiy

Reputation: 6209

You can use the following statement with regex:

if (/<[a-z][\s\S]*>/i.test(textareaContent)) {
  alert("html tags not allowed");
}

Kooilnc is right. You should always check user input on server side as well.

Please see this question Check if a string is html or not

Upvotes: 1

Related Questions