最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jquery validation to check text contains no html - Stack Overflow

programmeradmin3浏览0评论

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 server anyway)

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 server anyway)

Share Improve this question edited Feb 5, 2013 at 13:52 chiccodoro 14.7k20 gold badges91 silver badges132 bronze badges asked Mar 24, 2011 at 16:40 raklosraklos 28.5k60 gold badges189 silver badges306 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 12

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)

  1. 暂无评论