Reputation: 266
We have a simple Elementor form with one field for an email address and a submit button, for people to sign up to a newsletter.
I'm trying to add some custom validation to only allow submissions from .co.uk
, .gov.uk
, and gmail.com
email addresses, and prevent submission if the input doesn't match one of those.
The validation itself works, in the sense that it displays the custom error message when appropriate, but it's not preventing submissions despite calling e.preventDefault()
, e.stopPropagation();
, and return false;
.
Every thread I've looked at says this should work in theory but perhaps it's different with Elementor forms? Any ideas?
(function($) {
$(document).ready(function() {
const accepted = ['.co.uk', '.gov.uk', 'gmail.com'],
form = $('#mail_signup');
$(form).submit(function(e) {
$('.mail-form-invalid').remove();
const email = $('#form-field-email').val(),
valid = accepted.some(accepted => email.includes(accepted));
if (!valid) {
e.preventDefault();
e.stopPropagation();
$(form).after('<p class="mail-form-invalid" style="color: #f00;">Sorry, we only allow submissions from .co.uk, .gov.uk and gmail.com.</p>');
return false;
}
});
});
})(jQuery);
Upvotes: 1
Views: 2530
Reputation: 266
Thanks to Rory McCrossan's comment I was able to update my code to listen for the submit button click instead:
<script>
(function($){
$(document).ready(function(){
const accepted = ['.co.uk','.gov.uk','gmail.com'],
form = $('#mail_signup'),
input = $('#form-field-email'),
submit = $(form).find('button[type="submit"]');
function validate(e){
$('.mail-form-invalid').remove();
const email = $(input).val(),
valid = accepted.some( accepted => email.includes( accepted ) );
if (!valid) {
e.preventDefault();
e.stopPropagation();
$(form).after('<p class="mail-form-invalid" style="color: #f00; margin-top: 10px;">Sorry, we only allow submissions from .co.uk, .gov.uk and gmail.com.</p>');
return false;
}
}
$(submit).on('click',function(e){
validate(e);
});
});
})(jQuery);
</script>
Upvotes: 1