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";
                
            }
        }
Member Avatar for diafol

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.

Airshow

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.