0

I am using javascript to check if the fields in my form are not empty. Everything works great, it also checks on an amount of characters in a field.

But now I would like that the email field will be checked if it contains an '@' and at least one '.' otherwise it should give the (same) error message.

I hope someone can help me!

Fiddle:
http://jsfiddle.net/43vLT/1/

function isValid(fldId,len) {
var fld = $("#"+fldId);
var val = fld.val();
window.console && console.log(fld,fldId)
if (val == "" || (len && val.length<len)) {
  fld.css("borderColor","red");
  return false;
}      
fld.css("borderColor","black");
return true;
}

$(function() {
$("form").on("submit",function() {
var errormessage = [];

if (!isValid('naam', 10)) {
  errormessage.push("You forgot to fill in your name ");
}
if (!isValid('email')) {
  errormessage.push("You forgot to fill in your email ");
}

if (errormessage.length>0) {
  window.console && console.log("error present");
  $(".error-messages").html(errormessage.join('<br/>')).fadeIn();
  return false;
}
window.console && console.log("success");
return true;
});
});
Erwin van Ekeren
  • 710
  • 4
  • 13
  • 36
  • http://stackoverflow.com/questions/46155/validate-email-address-in-javascript – gvee Jan 14 '14 at 12:54
  • 1
    So you just want email validation? Could use regex: `/^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/` – gideonparanoid Jan 14 '14 at 12:55

2 Answers2

1

I wouldn't do this with just checking to see if it has an email address. I'd use an official regex for matching emails. However, if you can't use regex, use this

var str="name@example.com";
if(str.indexOf("@")===-1 ||str.indexOf(".")===-1){
    alert("Your email address must include one @ sign and one period");
}

The W3C uses this regex for its <input type="email"/>

/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/
scrblnrd3
  • 7,228
  • 9
  • 33
  • 64
1

Your best bet for validating emails would be a regular expression. There isn't really a great "one-size-fits-all" regex that will catch all valid types of emails, since the actual specification allows for quite some interesting addresses to exist, even though they aren't very popular and widely used. You could take a look this guide to regular expressions for matching emails

And in your isValid you can add something like this

if ('fldId' === 'email') {
    return /.+@.+\..+/.test(val);
}

The regex /.+@.+\..+/ just checks for anything that has some characters, and @, some more characters a dot and some more charaters after that. It's basically the most naive check for email addresses. You can change it for some of the better ones from the link.

Also, you could look into some html5 goodness. input fields with type=email will get somewhat automatically verified by modern web browsers and there's a pretty good chance they do a better validation than one could find dangling around on the web.

kunev
  • 63
  • 7