I am using ZeroBounce API for email validation to check for non-free emails. But the problem is that it is being submitted even when the email is invalid. It does show the error message but then the form is submitted. I have added the e.preventDefault()
in the custom code too.
Here’s my code:
<script>
// JavaScript Validation
document.getElementById('myForm').addEventListener('submit', function(event) {
event.preventDefault(); // Prevent form submission
var email = document.getElementById('email').value;
var emailInput = document.getElementById('email');
var request = document.getElementById('request').value;
// Check if email and request fields are not empty
if (email.trim() === '' || request.trim() === '') {
alert('Please fill in both email and integration request fields.');
return;
}
// Validate email using ZeroBounce API
validateEmail(email)
.then(function(response) {
console.log("Email: ", email);
console.log(response);
if (response.status === 'valid' && response.free_email === false) {
// Email is valid and not free, submit the form
alert('Form submitted successfully!');
document.getElementById('myForm').submit();
} else {
event.preventDefault();
alert('Please enter a valid and non-free email address.');
emailInput.focus();
return false;
}
})
.catch(function(error) {
console.error('Error:', error);
alert('An error occurred while validating the email address.');
emailInput.focus();
return false;
});
});
function validateEmail(email, ipAddress = '') {
var apiKey = 'apiKey';
var apiUrl = `https://api.zerobounce.net/v2/validate?api_key=${apiKey}&email=${encodeURIComponent(email)}&ip_address=${encodeURIComponent(ipAddress)}`;
return fetch(apiUrl)
.then(function(response) {
return response.json();
})
.then(function(data) {
return data;
})
.catch(function(error) {
console.error('Error:', error);
throw error;
});
}
</script>