Captcha Images on a Form

Last modified by Manuel Smeria on 2026/06/02 17:54

cogDisplay a captcha image on a form and verify the answer
TypeSnippet
Category
Developed by

Oana Florea

Rating
1 Votes
LicenseGNU Lesser General Public License 2.1

Table of contents

Description

The snippet below uses the captcha module bundled by default in XWiki to generate and verify captcha images.

Code

{{velocity}}
#if("$!request.create" == "1" && $!request.getMethod() == "POST")
    #set($isCaptchaVerified = false)
    #set($captchaVerifier = $captchaservice.getCaptchaVerifier('image'))
    #set($isCaptchaVerified = $captchaVerifier.isAnswerCorrect($captchaVerifier.getUserId($request), "$!request.captcha_answer"))
    #if($isCaptchaVerified)
      {{info}}Your answer is correct!{{/info}}
    #else
      {{error}}Your answer does not match!{{/error}}
    #end
  #end

  {{html}}
      <form id="myForm" name="myForm" method="post" class="xform" action="$doc.getURL('view')">
        <dl>
          <dt><span id="captcha-reload" style="color:#028BCD; cursor: pointer;">Refresh</span></dt>
          <dl><img id="captcha-image" style="border: solid 1px #000000;" src="$doc.getURL("imagecaptcha")"></dl>
          <dt><label for="captcha_answer">Your answer</label></dt>
          <dl> <input size="30" type="text" name="captcha_answer" /></dl>
        </dl>
        <input type="hidden" name="create" value="1" id="create" />
        <span class="buttonwrapper"><input type="submit" class="button" value="Submit"/></span>
      </form>
  {{/html}}
{{/velocity}}

Add a javascript skin extension on the wiki page to refresh the captcha image when needed:

var XWiki = (function (XWiki) {
// Start XWiki augmentation.
XWiki.MyForm = Class.create({
  initialize : function() {
    this.initCaptchaReload();
  },
  initCaptchaReload: function(){
    var myFormDoc = new XWiki.Document("$doc.space", "$doc.name", XWiki.currentWiki);
    $('captcha-reload').observe('click', function(event){
      var myFormDocURL = myFormDoc.getURL('imagecaptcha');
      $('captcha-image').src = myFormDocURL;
    });
  }
});
// End XWiki augmentation.
return XWiki;
}(XWiki || {}));

document.observe('xwiki:dom:loaded', function() {
  new XWiki.MyForm();
});

Result

Executing the code will give you:

captcha_answer.png

captcha_images.png

Get Connected