I am learning some javascript. I tried to write a trivial code to validate email but my code does not seem to work it should.

It should turn the background color of text box green when mail contains both '@' and '.' characters and red otherwise. However what the code does is turning it to green whenever there is a '@' not caring about the '.'.

What is wrong with the code ?

function CheckMail()
            var box = document.getElementById("email");
            var mail = box.value;
            var valid = true;
            if((mail.search("@") == -1) || (mail.search(".") == -1)) // If mail contains "@" and "." it is valid
                valid = false;
                box.style.background = "green";
                box.style.background = "red";
Member Avatar


Use regex to validate email addresses. Search js + regex + email.

I am just trying to learn some javascript, not to validate email. Can you see the problem with my code?

Tellalca, String.search expects its argument to be a regular expression.

Try String.indexOf instead, with arguments ("@") and (".") as you were trying.