How to filter bad words of textbox in ASP.NET MVC?

2.3k Views Asked by At

I have a requirement in which i wanna filter the textbox value, that is should remove the bad words entered by the user. Once the user enters the bad words and click on submit button, action is invoked. Somewhere in the model(any place) i should be able to remove the bad words and rebind the filtered value back to the model.

How can i do this?

1

There are 1 best solutions below

2
On

If you can update the solution to MVC 3 the solution is trivial. Just implement the word check in a controller and then apply the RemoteAttribute on the property that should be validated against bad words. You will get an unobtrusive ajax check and server side check with just one method and one attribute. Example:

public class YourModel
{
    [Remote("BadWords", "Validation")]
    public string Content { get; set; }
}

public class ValidationController
{
    public JsonResult BadWords(string content)
    {
        var badWords = new[] { "java", "oracle", "webforms" };
        if (CheckText(content, badWords))
        {
            return Json("Sorry, you can't use java, oracle or webforms!", JsonRequestBehavior.AllowGet);
        }
        return Json(true, JsonRequestBehavior.AllowGet);
    }

    private bool CheckText(string content, string[] badWords)
    {
        foreach (var badWord in badWords)
        {
            var regex = new Regex("(^|[\\?\\.,\\s])" + badWord + "([\\?\\.,\\s]|$)");
            if (regex.IsMatch(content)) return true;
        }
        return false;
    }
}