开发者

jquery validation to check text contains no html

How can I perform jquery validation to check if a textarea contains no html tags? (error if it does)

(BTW I am preventing html from coming through on the ser开发者_开发技巧ver anyway)


You could use John Resig's HTML parser (here), or maybe a more naive solution that just looks for opening tags.

$('textarea').each(function() {
   if ($(this).val().match(/<(\w+)((?:\s+\w+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/)) {
      alert('html found');
   }
});

Neal's solution suffers from false positives on textareas that contain valid jquery selectors, such as a textarea that contains just "a".


try this on for size:

$('textarea').each(function(){
    var text = $(this).text();
    if($(text).length > 0){
        console.log('contains html elements')
    }
    else {
        console.log('no html elements')
    }
});

fiddle is here

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜