captcha form validation required error message in vue-recaptcha

冷暖自知 提交于 2019-12-01 10:31:27

You can use a property (loginForm.recaptchaVerified below) to track if the recaptcha was verified and prevent submit + display a message if not:

JSFiddle demo: https://jsfiddle.net/acdcjunior/o7aca7sn/3/

Code below:

Vue.component('vue-recaptcha', VueRecaptcha);

new Vue({
  el: '#app',
  data: {
    loginForm: {
      recaptchaVerified: false,
      pleaseTickRecaptchaMessage: ''
    }
  },
  methods: {
    markRecaptchaAsVerified(response) {
      this.loginForm.pleaseTickRecaptchaMessage = '';
      this.loginForm.recaptchaVerified = true;
    },
    checkIfRecaptchaVerified() {
      if (!this.loginForm.recaptchaVerified) {
        this.loginForm.pleaseTickRecaptchaMessage = 'Please tick recaptcha.';
        return true; // prevent form from submitting
      }
      alert('form would be posted!');
    }
  }
})
<script src="https://www.google.com/recaptcha/api.js?onload=vueRecaptchaApiLoaded&render=explicit" async defer>
</script>
<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/vue-recaptcha@latest/dist/vue-recaptcha.js"></script>

<div id="app">
  <form v-on:submit.prevent="checkIfRecaptchaVerified">
     <div>
        <vue-recaptcha @verify="markRecaptchaAsVerified"
            sitekey="6Le-wvkSAAAAAPBMRTvw0Q4Muexq9bi0DJwx_mJ-">
        </vue-recaptcha>
     </div>
     Some other fields of the form here...
     <br>
     <button>Submit form</button>
     <hr>
     <div><strong>{{ loginForm.pleaseTickRecaptchaMessage }}</strong></div>
  </form>
</div>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!