0 Comments

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>

privatevoidInititializeCaptcha()

{

 if(ViewState["captchavalue"] ==null)

 {

   ViewState["captchavalue"] =Guid.NewGuid().ToString();

 }

 

 System.Text.StringBuildersb =newSystem.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>

privateboolIsCaptchaValid

{

 get

 {

   if(ViewState["captchavalue"] !=null)

   {

     returnRequest.Form["captcha"] == ViewState["captchavalue"].ToString();

   }

 

   returnfalse;

 }
}

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.

protectedvoidPage_Load(objectsender,EventArgse)

{

 InititializeCaptcha();

}

 

///<summary>

///Handles the submit buttons onclick event

///</summary>

voidbtnSave_Click(objectsender,EventArgse)

{

 if(IsCaptchaValid)

 {

   SaveComment();

 }
}