Pais
Pais

Reputation: 116

Why doesn't using the search method to find a . work the way I expect in JavaScript?

In my js code, I'm trying to validate an email address.

var validateEmail = function () {
    var email = $("email").value;
    var symbol = email.search("@");
    var domain = email.substring(email.indexOf('@')).substr(1);
    var validDomain = domain.search(".");

    if (symbol == -1) {
        alert(email + " is not a valid email address.");
    } else if (validDomain == -1) {
        alert(email + "is not a valid domain name.");
    } else {
        alert(email + " is a valid email address.");
    }

};

I'm sure there is a better way to validate an email address, but the way I'm doing it is to practice with js properties and methods. Learning simple basic stuff. Not even sure if this example is consider best practice.

The problem:

var validDomain = domain.search(".");

is not pulling the period from the string. Can someone point out the problem I'm having here.

Here's the jsfiddle: http://jsfiddle.net/UDv7q/

Upvotes: 2

Views: 157

Answers (1)

Ian
Ian

Reputation: 50933

The main problem is that search expects a regular expression be passed. If the argument isn't one, it's implicitly converted to one. . is a special character in regular expressions, so you'd need to escape it (you might as well use a regex literal).

var validDomain = domain.search(/\./);

DEMO: http://jsfiddle.net/h4hx5/

Note that this simple validation doesn't actually ensure the input is a valid email. There's a specification that defines what a valid email is, and it's quite a bit more complex than this. But if it works for you, that's great; it's usually hard to fully validate an email :)

Reference:

Upvotes: 3

Related Questions