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
精彩评论