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

后端 未结 3 806
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: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.

提交回复
热议问题