Thursday, July 17, 2014

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 user 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 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)] 
Validate input is true by default, and that is why it prevents execution of any code in case if there is 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       

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


Step 2
- Create custom attribute as below:

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:
[DenyHtmlInput]
public string Comments { get; set; }
That's it.

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

No comments:

Post a Comment

Thanks for visiting my blog.
However, if this helped you in any way, please take a moment to write a comment.

Thanks
Nirman