This page looks best with JavaScript enabled

Use Google Recaptcha in Vue Forms

 ·   ·  ☕ 2 min read

Google recaptcha is quite a powerful tool in reducing spam through our contact forms.

Once included in our forms, reCaptcha automatically manages suspicious activity, prompts additional ‘bot vs. human checks’, or is completely transparent to the overall flow - depending on who is interacting with the site.

Including reCaptcha in Vue is quite simple.

1. Install vue-recaptcha-v3

Install the NPM package called ‘vue-recaptcha-v3’. This will enable us to just plug and play recaptcha rather than including the 4-5 lines of code provided by Google.

2. Create the contact form

Create the Vue SFC that will house the contact form. Link to the form from the home page. An example with Vuetify is below.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<!-- Contact.vue -->

<template>
  <v-form ref="form" v-model="valid">
    <v-layout>
      <v-flex xs12>
        <span class="display-2">Contact Us</span>
      </v-flex>

      <v-flex xs12>
        <v-text-field
          label="Email"
          type="text"
          name="email"
          v-model="contactDetail['name']"
        ></v-text-field>
      </v-flex>
      <v-flex xs12>
        <v-text-field
          label="Message"
          type="text"
          name="message"
          v-model="contactDetail['message']"
        ></v-text-field>
      </v-flex>
      <v-flex xs12 offset-md6 md6 text-xs-right>
        <v-btn color="primary" @click="validateAndSubmit">Submit</v-btn>
      </v-flex>
    </v-layout>
  </v-form>
</template>
3. Include reCaptcha code

Code the logic for the submit button and embed reCaptcha functionality therein.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<!-- Contact.vue -->

<script>
  import Vue from "vue";
  import { VueReCaptcha } from "vue-recaptcha-v3";
  Vue.use(VueReCaptcha, { siteKey: "your-google-recaptcha-site-key" });
  export default {
    data() {
      return {
        valid: true,
        contactDetail: { email: "", message: "" },
      };
    },
    methods: {
      validateAndSubmit() {
        if (this.$refs.form.validate()) {
          this.disableSubmit = true;
          this.$recaptcha("contactus").then((token) => {
            this.parseContactInfo(this.contactDetail);
            // parse & store data. Method can be housed in Vuex store
            // show confirmation message

            router.push("/");
            // navigate to home page after processing  data
          });
        }
      },
    },
  };
</script>
The End Result

You now have a beautiful form that will not only apply your own validations for the form, but also checks whether reCaptcha is happy before submitting data to your back-end.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things