ASP.NET MVC - ValidateAntiSpamAtrribute


/ Published in: C#
Save to your folder(s)



Copy this code and paste it in your HTML
  1. public class ValidateAntiSpamAttribute : ActionFilterAttribute
  2. {
  3. public string ErrorMessage { get; set; }
  4.  
  5. public ValidateAntiSpamAttribute() { }
  6. public ValidateAntiSpamAttribute(string errorMessage)
  7. {
  8. this.ErrorMessage = errorMessage;
  9. }
  10.  
  11. public override void OnActionExecuting(ActionExecutingContext filterContext)
  12. {
  13. string sixtimesnine = (string)filterContext.HttpContext.Request.Form["sixtimesnine"];
  14. string fourtytwo = (string)filterContext.HttpContext.Request.Form["fourtytwo"];
  15.  
  16. if (string.IsNullOrEmpty(sixtimesnine) ||
  17. string.IsNullOrEmpty(fourtytwo) ||
  18. sixtimesnine != fourtytwo)
  19. {
  20. filterContext.Controller.ViewData.ModelState.AddModelError("Spam", this.ErrorMessage);
  21. }
  22. else
  23. {
  24. // Merely for unit testing puproses - we need to make sure that the above clause
  25. // was *not* run.
  26. filterContext.Controller.ViewData["filter"] = "passed";
  27. }
  28. base.OnActionExecuting(filterContext);
  29. }
  30. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.