0

Hey;

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;
            
            if(valid)
            {
                box.style.background = "green";
            }
            else
            {
                box.style.background = "red";
                
            }
        }
3
Contributors
3
Replies
4
Views
6 Years
Discussion Span
Last Post by Airshow
0

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

1

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

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

Airshow

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.