验证码表格验证需要在vue-recaptcha中显示错误消息

时间:2018-03-19 13:54:00

标签: vue.js laravel-5.6

我在vue.js和Laravel 5.6.7中关注此软件包以实现验证码。

https://github.com/DanSnow/vue-recaptcha#install

vue.js中的组件代码

<template>
    <div>        
        <vue-recaptcha  v-model="loginForm.recaptcha"
            sitekey="My key">
        </vue-recaptcha> 

        <button type="button" class="btn btn-primary">
            Login
        </button>                            
    </div>
</template>

<script>

</script>

app.js代码

import VueRecaptcha from 'vue-recaptcha';
Vue.use(VeeValidate);
Vue.component('vue-recaptcha', VueRecaptcha);

问题:

是否有任何vue-recaptcha属性需要调用才能显示表单验证消息?

1 个答案:

答案 0 :(得分:2)

您可以使用属性(下面的loginForm.recaptchaVerified)来跟踪重新验证是否已经过验证,如果没有,则阻止提交+显示消息:

JSFiddle演示:https://jsfiddle.net/acdcjunior/o7aca7sn/3/

以下代码:

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>