Thursday, 21 April 2016

Google recaptcha using javascript

Register your web site at Google recaptcha platform to get keys needed to code the form. Click here to go to Google reCAPTCHA website.
After signing in, add your website details.

After registration Google will provide you following :
  • Site key
  • Secret key
Creating Google reCAPTCHA form in HTML
Here is our HTML code to generate simple form with Google reCAPTCHA.

<form action="" method="POST" id="loginform" onsubmit=" return verifyCaptcha()">

<input id="email" maxlength="80" name="email" size="20" type="text" placeholder="Enter Your Email" style="margin-bottom: 30px;"/><br>
<div id="captchadiv">
<div class="g-recaptcha" data-sitekey="<!-- your site key here -->"></div>
<div style="width: 302px; height: 422px; position: relative;">
<div style="width: 302px; height: 422px; position: absolute;">
<iframe src="<!-- your site key here -->"
frameborder="0" scrolling="no"
style="width: 302px; height:422px; border-style: none;">
<div style="width: 300px; height: 60px; border-style: none;
bottom: 12px; left: 25px; margin: 0px; padding: 0px; right: 25px;
background: #f9f9f9; border: 1px solid #c1c1c1; border-radius: 3px;">
<textarea id="g-recaptcha-response" name="g-recaptcha-response"
style="width: 250px; height: 40px; border: 1px solid #c1c1c1;
margin: 10px 25px; padding: 0px; resize: none;" >

<button type="submit" value="Submit" />Sign in</button>

Client Side code

function verifyCaptcha(){
var captcha_response = grecaptcha.getResponse();

if(captcha_response.length == 0 || grecaptcha == undefined )
return false;
if(response == undefined && response.responseCode == undefined && response.responseDesc == undefined && response.responseCode !== 0 && response.responseDesc !== 'Sucess' ){
return false;

return true;

Server Side code

var requestQuery = req.query;
if( requestQuery != undefined && requestQuery != '' && requestQuery != null && requestQuery.response != undefined && requestQuery.response != '' && requestQuery.response != null ){
var response = requestQuery.response;
var verificationUrl = ""+ secret_key +"&response=" +response;
// Hitting GET request to the URL, Google will respond with success or error scenario.
request(verificationUrl,function(error,response,body) {
body = JSON.parse(body);
// Success will be true or false depending upon captcha validation.
if(body.success !== undefined && !body.success) {
res.send({"responseCode" : 1,"responseDesc" : "Failed captcha verification"});
res.send({"responseCode" : 0,"responseDesc" : "Sucess"});
res.send({"responseCode" : 1,"responseDesc" : "Failed captcha verification"});