Google reCAPTCHA validation

freelance web developer and web application development services in Bangalore

In this you can see how to make google captcha valifation in HTML form(s).In this we can see two methods of validation.

Method 1 : If using Jquery for form validation ,do the following stpes

STEP 1 :  Add the following script at before the </head> section

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

STEP 2 : Before that, register your site and get the sitekey for you website.

to get the key click here  and sign in your gmail account.

STEP 3 : Add the following code in your form where do you want to display the captcha.

<div class="g-recaptcha" data-sitekey="your-site-key"></div>

add you site key in above code.

STEP 4 : If you are using Jquery validation for your form add the below in your validation section. ie.after the variable declarations

if (grecaptcha.getResponse() == ""){

$("#error_message").show().html("ReCaptcha was not validated");

}

after the form submission give below to reset the captcha

grecaptcha.reset();

Method 2 :

If you aren’t using jquery validation and need js validation just add the below script in you html page or js file.

<script type="text/javascript">
function validateform(){
var captcha_response = grecaptcha.getResponse();
if(captcha_response.length == 0)
{
 // Captcha is not Passed
alert("Captcha validation failed");
 return false;
}
else
{
 // Captcha is Passed
 return true;
}
}
</script>

NOTE : Add the onsubmit=”return validateform();” in the form like below

 <form action="contact.php" method="post"  onsubmit="return validateform();">

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *