Adding Recaptcha verification to your form

We all create forms in your system & applications. If you are a web developer , you may experience once or more creating forms. For example contact form , registration form etc. Recaptcha is a free service supported by Google which helps to protect our websites from spam and abuse. Basically A “CAPTCHA” is a test to separate human and bots apart.

Today I will guide you how to add a reCAPTCHA service in your form easily.

First thing first, we need to generate a reCAPTCHA key to add in our form. You can go to this link and click + button to create a key.

This will proceed to a form to choose the options like this.

There are two versions of reCAPTCHA type for now , version 2 and 3. With reCAPTCHA v2, the only action required was to check if the user successfully solved the challenge or not. With reCAPTCHA v3, you must now decide what action to take based on the score. you may choose depending on your favour. In this tutorial , I will use v2 as I like its simplicity.

After filling up the form, you will get the reCAPTCHA site key like this.


For the source code part, we need to import the reCaptcha API JS in a script tag like this.

<script src=https://www.google.com/recaptcha/api.js></script>

And we can embed our site key in HTML.

<div class="g-recaptcha" data-sitekey="YOUR-SITE-KEY-HERE"></div>

Of course you can modify the css class as you like. For the validation, we can use grecaptcha.getResponse()function to validate the reCAPTCHA response. I will add a example code which is used in my project.

//This is just a sample code and can differ depending on your //source code.
if ($('.g-recaptcha').length > 0) {
   if (grecaptcha.getResponse() == "") {
      flag = 1;
        alert('Please verify Recaptch');
   } else {
      flag = 0;
   }
}

// You can also read the official documentation.
// https://developers.google.com/recaptcha/intro

As a final result on the browser, you will get a reCAPTCHA checkbox like this. This may also differ depending on your design preferences.

By Yuuma



アプリ関連ニュース

お問い合わせはこちら

お問い合わせ・ご相談はお電話、またはお問い合わせフォームよりお受け付けいたしております。

tel. 06-6454-8833(平日 10:00~17:00)

お問い合わせフォーム