简体   繁体   中英

Validate User-Input HTML Subset

I'm looking for a way to validate user-input HTML, similar to what you'd see in a comment form. The user's input should be limited to the most basic tags, such as p, ul, li, div, img. The only allowable attribute is style.

Validation can occur clients-side, via Javascript, or server-side, via Ruby. I'm hoping to find a Javascript library that can do this, or at least find several RegExes to do this.

Thanks for your suggestions.

You could use Sanitize to filter the HTML.

Using the example elements you listed in your question you would use something like this in your validation code:

Sanitize.clean(html,
    :elements => ['p', 'ul', 'li', 'div', 'img'],
    :attributes => {'
        'all' => ['style']
    }
)

As I mentioned in my comment above, allowing the style attribute could be dangerous especially if you allow <a> tags as it opens you up to clickjacking attacks if a user creates an invisible link that covers the entire page.

If you do want to allow <a> tags I would recommend banning style completely and perhaps adding rel=nofollow to user provided links:

Sanitize.clean(html,
    :elements => ['p', 'ul', 'li', 'div', 'img', 'a'],
    :add_attributes => {
      'a' => {'rel' => 'nofollow'}
    }
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM