Manually trigger form validation when executing request using javascript api

Hello,

I use javascript api to execute form request and I also use inline form validation. It’s to handle google invisible captcha.

var onloadCallback = function() {
    var recaptchas = document.querySelectorAll('.g-recaptcha');

    recaptchas.forEach(function(el) {
        if(el.dataset.size == 'invisible') {
            const form = el.closest('form');
            const submit = form.querySelector('[type="submit"]');
            grecaptcha.render(el, { 
                callback: function(token) { 
                    oc.request(form, 'onFormSubmit', {
                        error: function(data) {
                            console.log('error');
                            resetReCaptcha(form);
                        }
                    });
                } 
            });
            submit.addEventListener('click', function(e) {
                e.preventDefault();
                grecaptcha.execute(el);
            });
        } else {
            grecaptcha.render(el);
        }
    });
}

function resetReCaptcha(form) {
    var el = form.querySelector('.g-recaptcha');
    grecaptcha.reset(el);
}

Globally, it works well except that, as I have to use e.preventDefault() on click event in my submit button (in order to initialize captcha), the code that display form validation error in div with attribute [data-validate-for] is not triggered.

My question is, how can I manually trigger that code in my error function (next to the console.log(‘error’)

Thank you

I answer to myself as I found the solution. You have to put this.success(data) in the error function, like this :

oc.request(form, 'onFormSubmit', {
    error: function(data) {
        resetReCaptcha(form);
        this.success(data);
    }
});
2 Likes

Thanks for sharing the solution.