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.

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.

 

Next, we will implement Google reCAPTCHA v2 in form.

Include google API script in the application

here we are rendering reCAPTCHA explicitly using callback onload event.

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

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 Reply

avatar
  Subscribe  
Notify of