如何使用JS在Google recaptcha中获得自定义消息有效性?

时间:2016-07-21 09:36:16

标签: javascript jquery html5 recaptcha

如何在Google recaptcha中获得自定义消息的有效性?

如果用户在点击提交按钮之前没有或忘记检查Google Recaptcha复选框。将显示一条弹出消息,用户需要先检查复选框。

我有JS将验证输入文本框,它正在工作。但我不知道如何在Google Recaptcha中实现它

JS:

function InvalidMsg(textbox){
     if(textbox.validity.patternMismatch){
        textbox.setCustomValidity('Please enter your name here');
    } else if(textbox.validity.valueMissing){
         textbox.setCustomValidity('This field is required');
    } else {
                textbox.setCustomValidity('');
    }
    return true;
}

1 个答案:

答案 0 :(得分:0)

您必须使用reCaptcha验证响应回调。这样的事情:https://www.google.com/recaptcha/api.js?import = reCaptchaCallback& render = explicit'>

您还需要将错误消息附加到正在使用的reCaptcha容器中。



var RC2KEY = 'sitekey',
    doSubmit = false;

function reCaptchaVerify(response) {
    if (response === document.querySelector('.g-recaptcha-response').value) {
        doSubmit = true;
    }
}

function reCaptchaExpired () {
    /* do something when it expires */
}

function reCaptchaCallback () {
    grecaptcha.render('id', {
        'sitekey': RC2KEY,
        'callback': reCaptchaVerify,
        'expired-callback': reCaptchaExpired
    });
}

document.forms['form-name'].addEventListener('submit',function(e){
    if (doSubmit) {
        /* submit form or do something else */
    }
    else {
        /**
         * Show your error message here.
         * InvalidMsg function may not work.
         * recaptcha does not have properties you are checking for.
         */
    }
})