Ahmad Naser Turnkey Ecosystem Ahmad Naser
March 15, 2019

google recaptcha client side validation using javascript

Published in the Ahmad Naser ecosystem. Estimated reading time: 1 minute.

first create a new recaptcha v2 to your site

https://www.google.com/recaptcha/admin/create

second add  recaptcha  to form check

  <form method="post" action="contact.php" class="form-horizontal" role="form" onsubmit="return validateRecaptcha();">

third, add the following script to the form

            <div class="text-center margin-bottom">
                    <div class="form-group">
                <label for="inputMessage" class="col-sm-3 control-label">Human?</label>
                <div class="col-sm-9">
                   <div id="html_element"></div>
                </div>

                </div>
        
            
<div class="g-recaptcha" data-sitekey="your-site-key"></div>
<script type="text/javascript">
  var onloadCallback = function() {
     grecaptcha.render('html_element', {
          'sitekey' : 'your-site-key'
        });

  };
  function validateRecaptcha() {
    var response = grecaptcha.getResponse();
    if (response.length === 0) {
        alert("captcha validated");
        return false;
    } else {
       alert("validated");
        return true;
    }
}
</script>
 <script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer>
    </script>
            </div>

 

Thats all

Regards

Leave a Reply

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