Validate Google Captcha via JavaScript

Suppose You have Form Similar to the code below

<form id="myformId" class="col s12" action=""
       method="post"
      novalidate>
        <input placeholder="Name" id="mpfaqs-form-fieldset-input" type="text" name="username">
        <input placeholder="Email" id="mpfaqs-form-fieldset-input" type="text" name="useremail">
            <input placeholder="What is your question" id="mpfaqs-form-fieldset-input-question"
                   type="text" name="userquestion">
    <div class="g-recaptcha" data-sitekey="YOURSITEKEYxxxxx"></div>
        <input class="form-submit" type="Submit" name="" value="Submit a question">
</form>
<script src='https://www.google.com/recaptcha/api.js'></script>
<script src='https://www.google.com/recaptcha/api.js?hl=es'></script>

To Validate above Form through javascript we will use the the below code you can place it in the same file or create an external file for it and place the code

<script>
    requirejs([
        'jquery'
    ], function($) {

        $(document).on('submit', '#myformId', function(){
            var isSubmit = jQuery(this).valid() && grecaptcha.getResponse() != '';

            if (!isSubmit) {
                alert("Please fill captcha");
            }
            return isSubmit;

        });
    })
</script>

 

Leave a Reply

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