HTML tags are not allowed in textbox validation using Jquery

By Hardik Savani | June 12, 2016 | | 8293 Viewer | Category : Javascript jQuery


I have two example that prevent HTML tags are not allowed in textbox using focusout event of jquery. You can chose any if you think it is best for me. In the first example i use regular expression for prevent html tags in my textarea and in second example i user directly check with html tags. So you can check both and use

Example 1:

<html lang="en">

<head>

<title>Jquery - HTML Tag are not allowed in textarea</title>

<script type="text/javascript" src="//cdn.jsdelivr.net/jquery/1/jquery.min.js"></script>

</head>

<body>

<div class="container text-center">

<form>

<textarea class="box"></textarea>

<button>Submit</button>

</form>

<script>

$(".box").focusout( function(e) {

var reg =/<(.|\n)*?>/g;

if (reg.test($('.box').val()) == true) {

alert('HTML Tag are not allowed');

}

e.preventDefault();

});

</script>

</div>

</body>

</html>

Example 2:

<html lang="en">

<head>

<title>Jquery - HTML Tag are not allowed in textarea</title>

<script type="text/javascript" src="//cdn.jsdelivr.net/jquery/1/jquery.min.js"></script>

</head>

<body>

<div class="container text-center">

<form>

<textarea class="box"></textarea>

<button>Submit</button>

</form>

<script>

jQuery('.box').focusout(function(e){

var message = jQuery('.box').val();

if(/<(br|basefont|hr|input|source|frame|param|area|meta|!--|col|link|option|base|img|wbr|!DOCTYPE|a|abbr|acronym|address|applet|article|aside|audio|b|bdi|bdo|big|blockquote|body|button|canvas|caption|center|cite|code|colgroup|command|datalist|dd|del|details|dfn|dialog|dir|div|dl|dt|em|embed|fieldset|figcaption|figure|font|footer|form|frameset|head|header|hgroup|h1|h2|h3|h4|h5|h6|html|i|iframe|ins|kbd|keygen|label|legend|li|map|mark|menu|meter|nav|noframes|noscript|object|ol|optgroup|output|p|pre|progress|q|rp|rt|ruby|s|samp|script|section|select|small|span|strike|strong|style|sub|summary|sup|table|tbody|td|textarea|tfoot|th|thead|time|title|tr|track|tt|u|ul|var|video).*?>|<(video).*?<\/\2>/i.test(message) == true) {

alert('HTML Tag are not allowed');

e.preventDefault();

}

});

</script>

</div>

</body>

</html>