Hari Gillala
Hari Gillala

Reputation: 11916

Display Friendly Error Message When Html tag is entered in a text Box- MVC ASP.NET

I have requirement of validating user input in a text box. Whenever a html tag is entered it should display the same view with friendly error message like "Cannot enter html tags."

The ways I have tried so far are:

  1. [ValidateInput(true)] on the Controller- It comes up with error "Potentially dangerous request"
  2. [ValidateInput(false)] on the Controller- It stores the value in the database-(I don't want this)
  3. In the view Model I placed a tag for the property [RegularExpression ( "<([A-Z][A-Z0-9]*)\b[^>]*>(.*?)</\1>",ErrorMessage = "You have entered html…Html is not a valid input!" )]

any one had this this issue. If yes please let me know, how have you fixed that.

Thank you

Upvotes: 1

Views: 1984

Answers (3)

Hari Gillala
Hari Gillala

Reputation: 11916

It is working now by displaying the friendly error message. I have changed a little bit by adding Validateinput tag at the Post Action controller.

I have to add this in ViewModel

[AllowHtml]
[RegularExpression (@"^[^<>]*$", ErrorMessage = "You have entered html... Html is not a valid input!" )]
public string SomePropertyThatShouldNotAcceptHtml { get; set; }

In Action Controller

I have to add the tag in the Post Event

[Validateinput(false)]

Thanks Darin.

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

You could use the [AllowHtml] attribute:

[AllowHtml]
[RegularExpression (@"^[^<>]*$", ErrorMessage = "You have entered html... Html is not a valid input!" )]
public string SomePropertyThatShouldNotAcceptHtml { get; set; }

Obviously before storing in the database you should ensure that the contents is safe:

[HttpPost]
public ActionResult Save(MyViewModel model)
{
    if (!ModelState.IsValid) 
    {
        // the model is invalid => redisplay view
        return View(model);
    }

    // the model passed validation => store in the database    
    ...
    return RedirectToAction("Success");
}

And if you are afraid of XSS you could use the AntiXSS library which will filter out all the dangerous scripts from the HTML. You could even write a custom model binder which will perform this step and automatically assign only a safe HTML value to the property.

Upvotes: 3

mreyeros
mreyeros

Reputation: 4379

Good morning this looks like an excellent starting point to be able to handle your requirement. Check out this article.

Upvotes: 0

Related Questions