Simple method to avoid comment spam
We probably all know about the annoying captcha images that a lot of blogs uses for separating humans from machines (spam robots). I use a captcha image to avoid comment spam on this blog because I get a lot, but I really don’t like to use it. I don’t like the fact that it makes is more difficult for my visitors to write comments, which is my only way of measuring the quality of the individual posts.
What I want is an invisible unobtrusive captcha method that automatically makes sure the user is human. So I wrote a simple method that does just that. It works by adding a small JavaScript to the page that adds a hidden form field when the form is submitted. The value of the hidden field must be the same as a server-side variable to validate. There must also be a property that returns a Boolean value that indicates whether or not the user is human.
/// <summary>
/// Initializes the captcha and registers the JavaScript
/// </summary>
private void InititializeCaptcha()
{
if (ViewState["captchavalue"] == null)
{
ViewState["captchavalue"] = Guid.NewGuid().ToString();
}
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.AppendLine("function SetCaptcha(){");
sb.AppendLine("var form = document.getElementById('" + Page.Form.ClientID + "');");
sb.AppendLine("var el = document.createElement('input');");
sb.AppendLine("el.type = 'hidden';");
sb.AppendLine("el.name = 'captcha';");
sb.AppendLine("el.value = '" + ViewState["captchavalue"] + "';");
sb.AppendLine("form.appendChild(el);}");
Page.ClientScript.RegisterClientScriptBlock(GetType(), "captchascript", sb.ToString(), true);
Page.ClientScript.RegisterOnSubmitStatement(GetType(), "captchayo", "SetCaptcha()");
}
/// <summary>
/// Gets whether or not the user is human
/// </summary>
private bool IsCaptchaValid
{
get
{
if (ViewState["captchavalue"] != null)
{
return Request.Form["captcha"] == ViewState["captchavalue"].ToString();
}
return false;
}
}
Examples of use
To use the captcha you have to call InitializeCaptcha from the Page_Load handler. Then just check the IsCaptchaValid property before you save the comment.
protected void Page_Load(object sender, EventArgs e)
{
InititializeCaptcha();
}
/// <summary>
/// Handles the submit buttons onclick event
/// </summary>
void btnSave_Click(object sender, EventArgs e)
{
if (IsCaptchaValid)
{
SaveComment();
}
}
Comments
Comments are closed