I am not sure why my code doesn't trigger html5 form validation. I checked few posts here and implement their methods and none of them worked.
I am creating dynamic invisible reCaptcha forms and form validation is not working as it should be... I am not sure what is wrong and what did I do wrong...
Does someone knows the problem?
My code:
$(function () {
$("button.g-recaptcha").click(function (event) {
event.preventDefault();
var currentForm = $(this).closest("form");
if(currentForm[0].checkValidity()) {
grecaptcha.execute();
}
else{
grecaptcha.reset();
}
});
});
var onloadCallback = function () {
$("button.g-recaptcha").each(function () {
var el = $(this);
grecaptcha.render($(el).attr("id"), {
"sitekey": "MY SITE KEY",
"size": "invisible",
"badge": "inline",
"callback": function (token) {
$(el).parent().find(".g-recaptcha-response").val(token);
$(el).closest("form").submit();
}
}, true);
});
};
JS code for form submitting:
$("#sendMessageButton").click(function (e) {
e.preventDefault();
if ($('#contact_topic').val() == '') {
$('#contact_topic-button').popover({
trigger: 'manual',
html: 'true',
placement: 'top',
content: function () {
return messages.please_enter_the_required_fields_first;
}
}).popover('show');
setTimeout(function () {
$('.popover').fadeOut('slow', function () {
});
}, 2000);
return;
}
if ($('#contact_topic_subcategory').val() == '') {
$('#contact_topic_subcategory-button').popover({
trigger: 'manual',
html: 'true',
placement: 'top',
content: function () {
return messages.please_enter_the_required_fields_first;
}
}).popover('show');
setTimeout(function () {
$('.popover').fadeOut('slow', function () {
});
}, 2000);
return;
}
var client = clientBrowser();
$("#contact_os").val(client.os + ' ' + client.osVersion);
$("#contact_client").val(client.client + ' ' + client.version);
$("#contact_mobile").val(client.mobile);
$("#contact_cookies").val(client.cookieEnabled);
$("#contact_resolution").val(client.screenSize);
$("#contact_window").val(client.windowSize);
$("#contact-form").submit();
});
twig/html:
<div class="signup-form contact-form">
{{ form_start(form, { 'attr': {'id': 'contact-form'} }) }}
{{ form_label(form) }}
{{ form_errors(form) }}
{{ form_widget(form) }}
{% for flashMessage in app.session.flashbag.get('error') %}
<div class="captcha-alert">
<span class="icon-alert"> ! </span>
{{ flashMessage }}
</div>
{% endfor %}
<button id="sendMessageButton" class="btn btn--green">{{ "contact.send_message"|trans }}</button>
<div class="validationHolder g-recaptcha" id="contactRecaptcha"></div>
{{ form_end(form) }}
{#<div class="send-message">#}
{#<a href="" class="send-message-button" id="sendMessageButton">{{ "contact.send_message"|trans }}</a>#}
{#</div>#}
</div>
This is console log of events:
CALLING SUBMIT
INSIDE ON SUBMIT
IS FORM VALID: false