Andy Andy - 4 months ago 5
jQuery Question

Checking the format of an email address in a contact form

I'm using a simple form with a name, email and comment field to send messages from a webpage. There's a hidden title field as well which should be empty in order for the form to be submitted - spam protection if you like.

The JQuery code I am running the form through before submitting works ok, but is currently only looking for an "@" character in the email address field. What I want is a better check for a correctly formatted email address.

Here's the code.

$(function() {
$('.error').hide();
$(".button").click(function() {
// validate and process form here

$('.error').hide();
var name = $("input#name").val();
if (name == "") {
$("label#name_error").show();
$("input#name").focus();
return false;
}
var email = $("input#email").val();
if (!(email.indexOf('@') > 0)) {
$("label#email2_error").show();
$("input#email").focus();
return false;
}
var message = $("textarea#message").val();
if (message == "") {
$("label#message_error").show();
$("textarea#message").focus();
return false;
}
var title = $("input#title").val()
if(title !== "") {
$("input#title").focus();
return false;
}

var dataString = 'name='+ name + '&email=' + email + '&message=' + message;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "sendmail.php",
data: dataString,
success: function() {
$('#message_form').html("<div id='response'></div>");
$('#response').html("<div id='content_success_block' class='shadow_box'>")
.append("<div id='success_image'><img src='assets/misc/success.png'></div>")
.append("<div id='success_text'>Thanks for contacting us! We will be in touch soon.</div>")
.append("</div>")
.hide()
.fadeIn(2500, function() {
$('#response');
});
}
});
return false;
});

});


Any help is appreciated.

Answer

The one that has worked best for "me"

function validEmail(v) {
    var r = new RegExp("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?");
    return (v.match(r) == null) ? false : true;
}

¬°Important!

You should really read THIS. It provides a lot of information on Regex for Emails, and why there is not really a good "be all, end all" solution. In short, you have to determine what is best for your expected users.


Incorperated

}  
var email = $("input#email").val();  
if (!validEmail(email)) {
    $("label#email2_error").show();  
    $("input#email").focus();  
    return false;  
}  

Alternate Strategy you might try: I tend to check email on keypress timeout (thus allowing the ability to fade out submit button if not all fields are ready)