0

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.

3
  • The question refers to “html entities”, then “html tags”. They are two different things. The question should be edited to make it unambiguous which one is meant (or whether you mean both tags and entities). Commented Mar 1, 2015 at 13:42
  • The question still refers to “html special chars”. Commented Mar 1, 2015 at 13:57
  • @JukkaK.Korpela not both are same? Commented Mar 1, 2015 at 15:26

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. Here element denotes what??
1

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

Comments

0

removing html tags in comment

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.