Created
April 27, 2016 05:32
-
-
Save jackmcpickle/4c1c69c694b5d6b5389e035ca9eb4787 to your computer and use it in GitHub Desktop.
Ajax Email validation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var $contactForm = $('#contactForm'), | |
$submitButton = $('#submitForm'), | |
$message = $('.js-error-messages'), | |
$honeypot = $('.js-honey'), | |
$emailField = $('.js-email-field'); | |
var resetButton = function(timeout) { | |
setTimeout(function() { | |
$submitButton.text('Send').prop('disabled', false); | |
}, timeout); | |
}; | |
var honeypotEmpty = function() { | |
return $honeypot.val() === ''; | |
}; | |
var hasValue = function(index, element) { | |
return $(element).val() !== ''; | |
}; | |
var hasFieldValues = function() { | |
var numberOfFields = $('.form__field.required').length; | |
return $formFields.filter(hasValue).length === numberOfFields; | |
}; | |
var hasValidEmail = function() { | |
var regEx = /^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$/; | |
return regEx.test($emailField.val()); | |
}; | |
var validateForm = function() { | |
if (!honeypotEmpty()) { | |
$message.text('You are not a human'); | |
return; | |
} | |
if (!hasFieldValues()) { | |
$message.text('Please fill in all fields'); | |
return; | |
} | |
if (!hasValidEmail()) { | |
$message.text('Your email address is not valid'); | |
} | |
}; | |
var formValid = function() { | |
return (honeypotEmpty() && hasFieldValues() && hasValidEmail()); | |
}; | |
var postToMailer = function(e) { | |
e.preventDefault(); | |
$message.empty(); | |
validateForm(); | |
if (!formValid()) { return; } | |
$submitButton.text('Sending...').prop('disabled', true); | |
$.ajax({ | |
url: this.action, | |
method: this.method, | |
data: $(this).serialize(), | |
success: function(data) { | |
$submitButton.text('Sent'); | |
$message.text('Success:' + data); | |
resetButton(5000); | |
}, | |
error: function(jqXHR, textStatus) { | |
$message.text('Error: ' + textStatus); | |
resetButton(7000); | |
} | |
}); | |
}; | |
$contactForm.on('submit', postToMailer); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment