The goal of the code below is, if the email address in the text field is valid, the submit button becomes active.
I’ve had this work using blur but it does not seem to work with keyboard events.
Any ideas?
$(document).ready(function(){
// default values
var email = $("#newsletter_email");
var button = $("#subscribe");
var a = $(email).val();
var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
// disable submit
$(button).attr("disabled", "disabled");
$(button).css("background-color","#CCC");
$(email).keydown(function(event) {
if(filter.test(a)){
button.attr("disabled", "enable");
button.css("background-color","#663399");
}
});
});
Even if you make the event trigger on keyboard events, the rest of the method is incorrect.
You simply can’t validate all legal e-mail addresses with that regular expression, and there’s no sensible regular expression that can.
The only reliable way would be to perform an AJAX post of the data to your server, where you should perform an on-the-fly DNS lookup of the MX records (and if those don’t exist, an A or AAAA record) for the domain portion.
For what it’s worth, the reason it doesn’t actually work for
.keydown()is because the variableais only being set once at the start of the outer function – you need to move the call to$(email).val()inside the.keydown()handler so that its value is fetched each time a key is pressed.