0

I have a textbox on my website where I want to prevent any form of html input. I obviously already block it on the server side, but I also want to block it using javascript for multiple reasons. I did a quick Google search to see if there was some ready made function available but I couldn't find any.

Does anyone know how to do this?

Edit: Sorry if the question was not clear. I basically want to show an error when the user types html into the textbox and then tries to submit the form. The server is already programmed to reject HTML input from the textbox but I also want to prevent it on the client-side.

TheGateKeeper
  • 4,420
  • 19
  • 66
  • 101

1 Answers1

2

HTML

<textarea id='noHTML'></textarea>

JS

var ta = document.getElementById('noHTML');

ta.onkeyup = function (e) {
 var val = this.value;


    // alternate regexp /<\/*(p|div|span)\s*.*>/g  
   // fill the above regex with all html tags 
 if(val.match(/<\/*[^<>]\s*.*>/g)) { 
  // alert('no html');
  // don't want an alert ? you can replace all html expressions

  // alternate syntax for all entities
  //  this.value = val.replace(/&/g, "&amp;").replace(/>/g, "&gt;").replace(/</g, "&lt;").replace(/"/g, "&quot;");
  // its long and slow but the choice is yours
  this.value = val.replace(/</g, '&lt;').replace(/>/g, '&gt;');  
 }

}

You can test and play with it at jsfiddle;

it's a light solution to your problem. my suggestion to you is to replace the entities during the form submission or if you don't want it at all you can alert the user on input.

Jay Harris
  • 4,201
  • 17
  • 21
  • But I don't understand, are we trying to prevent post if tags exist? Why can't we just replace the special chars with their HTML entities. – Ian Clark Jul 26 '13 at 21:17
  • Don't get me wrong, this would be a good solution if you wanted to stop users from posting, but you could just do something like [this](http://stackoverflow.com/questions/784586/convert-special-characters-to-html-in-javascript) to change all the characters you need. – Ian Clark Jul 26 '13 at 21:20
  • @IanClark i check that question and added in the option via comment block. just wanted to leave the option to the questionaire – Jay Harris Jul 26 '13 at 21:34
  • Thanks man, I used the regex expression you provided to detect HTML and show a warning. Cheers :). – TheGateKeeper Jul 27 '13 at 14:45
  • great, glad I could provide some assistance. since that was what you used I'll shrink my answer to reflect that – Jay Harris Jul 27 '13 at 14:58