Add reCAPTCHA v2 and Form Validation using Custom jQuery

In this post, we will create a form having custom validation for required fields using jQuery. This custom form will also have reCAPTCHA v2 of Google to verify if the user is a bot or real person.

Custom Validation on forms helps in a situation where we want to submit information using AJAX and don’t want to refresh the page. In that case, we can verify if the user has filled all fields with the required attribute or not if not then we can show a custom message or highlight fields are missed. Google’s reCAPTCHA v2 in form can be implemented using JavaScript API which we are going to implement ahead.

Let’s start with our custom validation form with Google’s reCAPTCHA v2 bot verification.

First add following HTML to create a form with three fields for email, name, and phone. There is also an element with ID google_recaptcha  to load Google reCAPTCHA.

  <div class="form-wrapper-outer">

    <form action="#" method="POST" name="htmlform" id="test-form" novalidate>
      <div class="field-wrapper">
        <div id="message-wrap">
          <span></span>
        </div>
      </div>
      <div class="field-wrapper">
        <input type="email" name="email" class="form-checkfield" id="" required>
        <div class="field-placeholder"><span>Enter your email</span></div>
      </div>
      <div class="field-wrapper">
        <input type="text" name="name" class="form-checkfield" id="" required>
        <div class="field-placeholder"><span>Enter your name</span></div>
      </div>
      <div class="field-wrapper">
        <input type="text" name="phone" class="form-checkfield" id="" required>
        <div class="field-placeholder"><span>Enter your phone</span></div>
      </div>
      <div class="field-wrapper">
        <div id="google_recaptcha"></div>
      </div>
      <div class="field-wrapper">
        <input type="button" id="submit-test-form" value="Submit">
      </div>
    </form>

  </div>

For form and validation styling add following CSS. In this form, I have used Gmail style floating placeholder which is optional and you can safely remove that.

    .form-wrapper-outer{
            padding: 40px;
            border-radius: 8px;
            margin: auto;
            width: 460px;
            border: 1px solid #DADCE0;
            margin-top: 7%;
        }

        .field-wrapper{
            position: relative;
            margin-bottom: 15px;
        }
        
        .field-wrapper input{
            border: 1px solid #DADCE0;
            padding: 15px;
            border-radius: 4px;
            width: 100%;
        }

        .field-wrapper input:focus{
            border:1px solid #1A73E8;
        }

        .field-wrapper .field-placeholder{
            font-size: 16px;
            position: absolute;
            /* background: #fff; */
            bottom: 17px;
            -webkit-box-sizing: border-box;
            box-sizing: border-box;
            color: #80868b;
            left: 8px;
            padding: 0 8px;
            -webkit-transition: transform 150ms cubic-bezier(0.4,0,0.2,1),opacity 150ms cubic-bezier(0.4,0,0.2,1);
            transition: transform 150ms cubic-bezier(0.4,0,0.2,1),opacity 150ms cubic-bezier(0.4,0,0.2,1);
            z-index: 1;

            text-align: left;
            width: 100%;
        }        
        
        .field-wrapper .field-placeholder span{
            background: #ffffff;
            padding: 0px 8px;
        }

        .field-wrapper input:not([disabled]):focus~.field-placeholder
        {
            color:#1A73E8;
        }
        .field-wrapper input:not([disabled]):focus~.field-placeholder,
        .field-wrapper.hasValue input:not([disabled])~.field-placeholder
        {
            -webkit-transform: scale(.75) translateY(-39px) translateX(-60px);
            transform: scale(.75) translateY(-39px) translateX(-60px);
            
        }


        .field-wrapper.field-error{
          border: 1px solid red;
        }
        .field-wrapper.field-error .field-placeholder span{
          color: red;
        }

        #message-wrap {
            padding: 15px;
            text-align: center;
            display: none;
            border-radius: 4px;
        }

        #message-wrap.success-msg{
          color:green;
          background: #e3ffd5;
        }
        #message-wrap.error-msg{
          color:red;
          background: #ffd5d5;
        }

 

Next, we will implement Google reCAPTCHA v2 in form.

Include google API script in the application

  <script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer>
  </script>

here we are rendering reCAPTCHA explicitly using callback onload event.

Now add following script code with reCAPTCHA initialization function and jQuery form validation methods.

    var onloadCallback = function() {
        grecaptcha.render('google_recaptcha', {
          'sitekey' : '6LfFSIUUAXXXXXXXXXXXDk7giXSN6Y8'
        });
      };
      
      $(function () {
        //Check if required fields are filled
        function checkifreqfld() {
                var isFormFilled = true;
                $("#test-form").find(".form-checkfield:visible").each(function () {
                    var value = $.trim($(this).val());
                    if ($(this).prop('required')) {
                        if (value.length < 1) {
                          $(this).closest(".field-wrapper").addClass("field-error");
                          isFormFilled = false;
                        } else {
                          $(this).closest(".field-wrapper").removeClass("field-error");
                        }
                    } else {
                        $(this).closest(".field-wrapper").removeClass("field-error");
                    }
                });
                return isFormFilled;
          }

        //Form Submit Event
        $("#submit-test-form").click(function () {
            if (checkifreqfld()) {
              event.preventDefault();
              var rcres = grecaptcha.getResponse();
              if(rcres.length){
                grecaptcha.reset();
                showHideMsg("Form Submitted!","success");
              }else{
                showHideMsg("Please verify reCAPTCHA","error");
              }
            } else {
                showHideMsg("Fill required fields!","error");
            }
        });

        //Show/Hide Message
        function showHideMsg(message,type){
          if(type == "success"){
            $("#message-wrap").addClass("success-msg").removeClass("error-msg");
          }else if(type == "error"){
            $("#message-wrap").removeClass("success-msg").addClass("error-msg");
          }

          $("#message-wrap").stop()
          .slideDown()
          .html(message)
          .delay(1500)
          .slideUp();
        }


        //Google Style InputFields
        $(".field-wrapper .field-placeholder").on("click", function () {
          $(this).closest(".field-wrapper").find("input").focus();
        });
        $(".field-wrapper input").on("keyup", function () {
          var value = $.trim($(this).val());
            if (value) {
              $(this).closest(".field-wrapper").addClass("hasValue");
            } else {
              $(this).closest(".field-wrapper").removeClass("hasValue");
            }
        });
      });

please find inline comments for more clarification on different methods in the code above.

To load reCAPTCHA v2 you need your own key which you need to place in sitekey  Check here to know How to get reAPTCHA key?

After completing all the above steps final form will look like this.

 

Leave a Comment

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