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

后端 未结 3 807
Happy的楠姐
Happy的楠姐 2021-01-07 08:30

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 htm

相关标签:
3条回答
  • 2021-01-07 08:49

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

    0 讨论(0)
  • 2021-01-07 08:50

    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.

    0 讨论(0)
  • 2021-01-07 09:11

    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.

    0 讨论(0)
提交回复
热议问题