Click here to Skip to main content
15,881,172 members
Articles / Web Development / HTML5

MVC Attribute to Restrict Users to Enter Any Kind of HTML Tags in the Input Fields

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
18 Aug 2015CPOL1 min read 8.5K   4  
MVC attribute to restrict users to enter any kind of HTML tags in the input fields

By default, if a user tries to enter any HTML tags in any of the input boxes in an MVC website, it will throw an error saying "Potentially dangerous request".

This is OK, as it doesn't allow users to enter HTML tags and prevents the site from security threat.

However, the error page is not user friendly, and it is not giving a clue to the user as to what was wrong there. So you may need to avoid default error page of browser, and instead your custom validation message should be displayed.

Also, there may be circumstances when you want to allow some fields to accept HTML tags (such as rich text boxes), and rest of the input fields shouldn't allow HTML. In that case, this approach will help.

In order to achieve this, we need to create an attribute in MVC and then can decorate Model properties with that attribute.

Step 1

Decorate HttpPost method with [ValidateInput(false)].

ValidateInput is true by default, and that is why it prevents execution of any code in case any HTML input values are detected in posted data.

Here, we need to set it to false as we would like to execute code of our custom attribute.

C#
[HttpPost]
[ValidateAntiForgeryToken]
[ValidateInput(false)]
public virtual ActionResult CreateCustomer(Customer viewModel)
{
......
}

Step 2

Create custom attribute as below:

C#
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;using System.Text.RegularExpressions;

public class DenyHtmlInputAttribute: 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
(String.Format("{0} cannot contain html tags", validationContext.DisplayName));}
}

Step 3

Decorate all input fields of your Model with the attribute created above:

C#
[DenyHtmlInput]
public string Comments { get; set; }

That's it.

This is how you can restrict HTML inputs on specific fields of your MVC view.

License

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


Written By
Unknown
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --