Click here to Skip to main content
15,886,067 members
Articles / Web Development / ASP.NET
Tip/Trick

Validating User Input Containing HTML tags in ASP.NET MVC

Rate me:
Please Sign up or sign in to vote.
4.64/5 (8 votes)
6 Mar 2013CPOL2 min read 43.7K   525   16   8
If you need that validation message saying: "Input field should not contain HTML...” then this short tip is for you!

Introduction

There was a need for checking that user input does not contain any tags and display a corresponding validation message. As you may know ASP.NET has a built in feature for verifying if the HTTP request has a potentially dangerous content, that is called Request validation. By default it is true in ASP.NET MVC for security reasons.

So how do we overpass this and create our custom validation mechanism for verifying that user input contains HTML code...

I have attached a sample project where this mechanism is implemented. This tip/example gives only the basic understanding of how to implement your own custom validation attribute for verifying the input. Also only server side validation happens in this example.

Let the code speak

I'll shortly describe the code from the sample project below:

First of all we have to create a custom validation attribute for checking if the model's property value has any HTML/XML tags. Let's call our custom attribute DisallowHtmlAttribute. To implement our validation logic we should override the IsValid method and place the logic there. Here is how it looks:

C#
public class DisallowHtmlAttribute : ValidationAttribute 
{
   protected override ValidationResult IsValid(object value, ValidationContext validationContext)
   {
	if (value == null)
           return ValidationResult.Success;

        var tagWithoutClosingRegex = new Regex(@"<[^>]+>");

        var hasTags = tagWithoutClosingRegex.IsMatch(value.ToString());

        if (!hasTags)
            return ValidationResult.Success;

        return new ValidationResult("The field cannot contain html tags");
   }
}

Okay, we've created our custom validation attribute, however we should have some mechanism for adding this validation attribute to all properties of the model that is passed to the view.

This can be done by creating our own custom DataAnnotationsModelValidatorProvider that will be adding and returning our DisallowHtmlAttribute to the list of modal validators. Let's call it DisallowHtmlMetadataValidationProvider and let's check its implementation:

C#
public class DisallowHtmlMetadataValidationProvider : DataAnnotationsModelValidatorProvider
{
    protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, 
       ControllerContext context, IEnumerable<Attribute> attributes)
    {
        if (attributes == null)
            return base.GetValidators(metadata, context, null);
        if (string.IsNullOrEmpty(metadata.PropertyName))
            return base.GetValidators(metadata, context, attributes);
        //DisallowHtml should not be added if a property allows html input
        var isHtmlInput = attributes.OfType<AllowHtmlAttribute>().Any();
        if (isHtmlInput)
            return base.GetValidators(metadata, context, attributes);
        attributes = new List<Attribute>(attributes) { new DisallowHtmlAttribute() };
        return base.GetValidators(metadata, context, attributes);
    }
}

Now we have to add DisallowHtmlMetadataValidationProvider to the MVC's current application validator provider. Such things are usually done in Global.asax:

C#
protected void Application_Start()
{ 
    AreaRegistration.RegisterAllAreas();
    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);
    //registering our custom model validation provider
    ModelValidatorProviders.Providers.Clear();
    ModelValidatorProviders.Providers.Add(new DisallowHtmlMetadataValidationProvider());
}

We are almost there. The only thing we have to do now is to disable the request validation, but first let's see how currently the site behaves when the user's input contains HTML/XML tags. Let's enter something like this:

Image 1

This is what we get after posting data to the server:

Image 2

This is the correct behavior because we haven't disabled the request validation in the application. We can easily disable the request validation for all Controller and Actions by registering ValidateInputAttribute with the false parameter in the global action filters in the Global.asax file.

C#
filters.Add(new ValidateInputAttribute(false));

Or if you need to disable Request validation only for a specific controller or action, just decorate it with:

C#
[ValidateInput(false)]

Now we are done and every time the user input contains an HTML or XML tag he'll see a validation message:

Image 3

Simple as that!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Ukraine Ukraine
I'm a .Net Developer. Love exploring and trying out new things.

Comments and Discussions

 
QuestionNot working for WebAPI Controller methods Pin
Member 1502368617-Dec-20 20:36
Member 1502368617-Dec-20 20:36 
QuestionDoes not show the Validation message Pin
HetJOshi7-Jun-16 7:09
HetJOshi7-Jun-16 7:09 
GeneralMy vote of 5 Pin
DudaCodeProject15-May-13 3:15
DudaCodeProject15-May-13 3:15 
GeneralMy vote of 5 Pin
Carsten V2.06-Dec-12 8:12
Carsten V2.06-Dec-12 8:12 
GeneralRe: My vote of 5 Pin
Daniel Killyevo6-Dec-12 21:09
Daniel Killyevo6-Dec-12 21:09 
GeneralMy vote of 5 Pin
esonparedes27-Nov-12 13:42
esonparedes27-Nov-12 13:42 
GeneralRe: My vote of 5 Pin
Daniel Killyevo29-Nov-12 11:16
Daniel Killyevo29-Nov-12 11:16 
GeneralRe: My vote of 5 Pin
esonparedes2-Dec-12 12:56
esonparedes2-Dec-12 12:56 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.