Testing for HTML Text Using Regular Expression


/ Published in: JavaScript
Save to your folder(s)

Use this to validate if input has html elements


Copy this code and paste it in your HTML
  1. //Testing for html in input box value
  2. //e.g. '<script>' will validate true and be unsafe for processing
  3.  
  4. alert(/^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/.test($j('#sometxt').val()) ? 'unsafe' : 'safe');
  5.  
  6.  
  7. <input type="text" id="sometxt" \>
  8.  
  9. //For PHP. Will validate to true and unsafe
  10.  
  11. $val = '<script>do.bad();</script>';
  12.  
  13. $patt = "/^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/";
  14.  
  15. echo preg_match($patt,$val) ? 'unsafe' : 'safe';

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.