This example is a step by step instruction on how to use a remote validator to verify a Google reCAPTCHA.
You don't need to follow this instruction anymore.
FormValidation now provides recaptcha1 and recaptcha2 add-ons adding support for Google reCAPTCHA v1
and v2 in a quick and more easy way.
Registry keys
You need to register a public and private keys provided at Get reCAPTCHA page.
Showing the captcha
Assume that the captcha will be placed inside an element with id of
recaptcha as following:
Google reCAPTCHA allows using either Non-Javascript or Ajax API to show up the recaptcha
image. In this example, we will use the reCAPTCHA Ajax
API.
reCAPTCHA then creates a text box with name of recaptcha_response_field. We
use the addField() method to add this field:
At the moment, the captcha field uses only notEmpty
validator indicating that the field is required. We will use the remote validator to verify it in the next step.
Currently, if you leave the captcha empty and submit the form, the field will be masked
as invalid. But the element showing captcha seem to be shown not properly, because the
feedback icon is placed right after the field:
In order to fix this, we need to move the feedback icon right after the
recaptcha element. It can be done by triggering the added.field.fv event, which is called after adding a
field:
Now, try to submit the form, and you will see that the feedback icon is shown at the
desired position:
Verifying the captcha
The last step is to validate the captcha using the remote validator. Google reCAPTCHA requires the value
of recaptcha_response_field and recaptcha_challenge_field
fields. The last one is a hidden field generated by Google reCAPTCHA.
So, we need to send these fields to our back-end:
Google reCAPTCHA provides many libraries in different languages to help us verify the
captcha based on recaptcha_response_field and
recaptcha_challenge_field values.
To simply demonstrate the back-end verifying process, I use the reCAPTCHA PHP library
which can be downloaded here.
Of course, you can use your own solution to verify the captcha as long as the back-end
need to return an encoded JSON containing the valid key.