With the growing use of technology people are getting smarter and smarter but not only people bots, software and hackers too that can even build or destroy the whole empire in a few seconds. Fighting against these spammers is tough and we are not alone.
That’s why Google reCAPTCHA has been introduced to reduce human efforts for preventing spams in online stores. This reCAPTCHA is a completely free service that protects your website from spam and abuse. It uses an advanced risk analysis engine and adaptive CAPTCHAs to keep automated software from engaging in abusive activities on your site. It does this while letting your valid users pass through with ease.
For upcoming Magento 2.x versions, Magento has planned to include this reCACPTCHA inside the package but what about the stores that are currently running in Magento 1.x? Yes, sometimes we have to also need to bind this reCAPTCHA along with our custom store forms to reduce spam. Today we are back with some exciting piece of code that will help you to Install Google reCACPTCHA on Magento custom form.
To do the same, First, we need to put below code inside custom form file where you want to bind Google reCACPTCHA.
<pre class="lang:default decode:true"> <li id="rcode"> <div class="captcha"> <div class="g-recaptcha" data-sitekey="<?php echo $this->helper('recaptcha')->getKey(); ?>" data-theme="<?php echo($this->helper('recaptcha')->getTheme()); ?>"></div> </div> <span id="captcha-required" style='display:none; color:#ff0000'><?php echo $this->__('Please Fill Recaptcha To Continue'); ?></span> </li> </pre>
Now, we need to create or put “onSubmit” event on form tag that will return javascript function to validateRecaptcha() function by adding following line like below.
<pre class="lang:default decode:true"> <form method="post" action="" id="loginForm" autocomplete="off" onsubmit="return validateRecaptcha()"> </pre> After that, we need to put below code at the bottom of same file. <pre class="lang:default decode:true"> <script type="text/javascript"> function validateRecaptcha() { if (grecaptcha.getResponse() != "") { document.getElementById("captcha-required").style.display = "none"; return true; } else { document.getElementById("captcha-required").style.display = "block"; return false; } return true; } </script> <script src='https://www.google.com/recaptcha/api.js'></script> </pre>
After that, we need to put below code at the bottom of same file.
That’s it. You have successfully bind Google reCACPTCHA with your Magento store custom form. Also, you are free to use this code anywhere inside your Magento form as per need.
Happy Coding!