sass
sass

Reputation: 87

Want to validate email address in JavaScript but can't figure out how to include only one @ in the character string

So far I have this:

function validateForm() {
var str=document.forms["myForm"]["email"].value;
var atpos=str.indexOf("@");
var dotpos=str.lastIndexOf(".com");
   if (atpos>0 || dotpos<atpos+2 || dotpos+2>=str.length) 
 {
   alert("Incorrect e-mail address");
   return false;
  }
}

How can I include the '@' to be shown ONCE in the character string? (So an email can't be validated as @@).

I also would appreciate it if it were anything but the regex method.

Upvotes: 0

Views: 94

Answers (4)

KarelG
KarelG

Reputation: 5234

If you don't want use regex, you can split a string by an occurrence.

var email = "[email protected]";
if((email.split('@').length != 2) {
    // it's not an email address
}
else {
    // it is an email address
}

Upvotes: 3

Tommi Gustafsson
Tommi Gustafsson

Reputation: 1860

The best way to validate the email address is through regular expressions:

/^\w+([\-+\.']\w+)*@\w+([\-\.]\w+)*\.\w+([\-\.]\w+)*$/

If you do not know regular expressions, I suggest that you learn them right away, since they are a pretty powerful and useful feature when dealing with and validating string content.

Upvotes: 0

PurkkaKoodari
PurkkaKoodari

Reputation: 6809

A nice hack is to check if the first @ is also the last @.

if(str.indexOf('@') != -1 && str.indexOf('@') == str.lastIndexOf('@')){
    // email is valid
} 

Upvotes: 1

Qubaish Bhatti
Qubaish Bhatti

Reputation: 728

Check this buddy

function validateForm()
{
    var x=document.forms["myForm"]["email"].value;
    var atpos=x.indexOf("@");
    var dotpos=x.lastIndexOf(".");
    if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
    {
        alert("Not a valid e-mail address");
        return false;
    }
}

Upvotes: 0

Related Questions