Nirman
Nirman

Reputation: 6783

How to allow a text box accepting only specific HTML tags?

I am having a textbox in my MVC view, that allows user to input HTML tags, but only few tags (such as, B, I, U, and A). For this, I have set ValidateInput attribute on my POST action to False, so it allows users to input HTML tags. But now I want to restrict users to input other HTML tags such as (INPUT, SCRIPT, etc). I mean, anything except the ones which I want to allow.

I guess, one way is to use a regex, but I am unable to find a proper regex for this.

Any idea of how to achieve this? Any help on this much appreciated.

Thanks and Regards

Upvotes: 0

Views: 890

Answers (1)

JotaBe
JotaBe

Reputation: 39025

That's dangerous, man. Your users could still insert undesired tags using some tricks, for example encoding data. Even if you try to think all the possible ways a user can employ to enter "dangerous" tags in your code, he'll find an additional one.

So you should try to look some kind of proven solution for your problem. Look for HTML sanitizer, for example Google ASP.NET MVC sanitize html input and you'll find several solutions. AntiXSS library could be a good solution: now it's called Microsoft Web protection Library. You can include it in your solution as a NuGet package:

Install-Package AntiXSS

I recommend you to read this article to get a deeper view of the problem and its solutions:

.NET HTML Sanitation for rich HTML Input

In this article you'll find that AniXSS and a less restrictive solution with full explanation of pros, cons, and how it all works. Don't miss the references in the comments.

Upvotes: 1

Related Questions