5

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.

Andy
  • 1,422
  • 5
  • 27
  • 43

4 Answers4

16

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)

SpYk3HH
  • 22,272
  • 11
  • 70
  • 81
  • Thanks, how could I incporporate that into what I already have? – Andy Apr 16 '12 at 16:53
  • Nice, I'll definitely give both a try. – Andy Apr 16 '12 at 17:37
  • FYI, when referring to `keypress timeout` i'm referring to [this technique](http://spyk3lc.blogspot.com/2012/03/helpful-hints-javascriptjquery-knowing.html) – SpYk3HH Apr 16 '12 at 17:45
  • After giving that code a try, it returned an error if I didn't include an after the '@' character. However, if I typed any sequence of characters after the '@' it didn't return an error even though there was no '.com' or other domain present for an email address. Maybe it's my implementation of the function which I dropped in above the code that I posted. – Andy Apr 17 '12 at 12:00
  • that's why I included the link "you should read [THIS](http://www.regular-expressions.info/email.html)". If you follow that link and read the whole article, you'll understand why "one regex to rule them all" is almost impossible for emails, since email addies can come in so many flavors. The regex i proposed is the "most all inclusive" for email checking, but if you want it narrowed down to a .com and/or .net, its easy to add at the end of that regex. To be all inclusive and check for specifics would really mean multiple regex matches back to back and that could get very harry, lol. – SpYk3HH Apr 17 '12 at 12:17
2

Call that function onBlur event of that text box, where you want to chk a valid email.

 function validateForm()
{
 var x = document.getElementById('txtEmail');
 var atpos=x.value.indexOf("@");
 var dotpos=x.value.lastIndexOf(".");
 if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
  {
    alert("Not a valid e-mail address");
    return false;
  }
}
QasimRamzan
  • 397
  • 3
  • 16
1

Just Stating a more obvious function that returns true or false when the email value is tested. Using the regExp.test(value)

 var emailIsValid =  function(value){
        var regex = new RegExp ("^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$");
        return regex.test(value);
    }

var email = $("input#email").val();  
        if (!emailIsValid(email)) {
           $("label#email2_error").show();  
           $("input#email").focus();  
        return false;  
        }  
jackotonye
  • 3,537
  • 23
  • 31
-1

The problem with Regex above (SpYk3HH) is that it validats somthing like: .me@gmail.c i think the best way is to use some ajax to call a PHP function (if you use PHP indeed) something like this:

if(!filter_var($email, FILTER_VALIDATE_EMAIL))
echo "Email Not Valid ! ";
timmz
  • 2,194
  • 3
  • 23
  • 29