简体   繁体   中英

Checking For HTML Using Javascript

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM