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";
                
            }
        }

Dani AI

Generated

The problem is that String.search expects a regular expression. When you call mail.search(".") the . is treated as the regex "any character", so it will match almost any non-empty string (usually returning 0). That makes your dot check effectively always succeed, so the only real check left is the @. As pointed out, use indexOf (or includes) for simple substring checks; was also right that a regex is the right tool for real validation.

A small, direct fix (uses indexOf, trims whitespace, and avoids the regex pitfall):

function checkMail() {
  var box = document.getElementById('email');
  var mail = box.value.trim();
  var hasAt = mail.indexOf('@') !== -1;
  var hasDot = mail.indexOf('.') !== -1;
  if (hasAt && hasDot) {
    box.style.background = 'green';
  } else {
    box.style.background = 'red';
  }
}

A slightly better quick-check makes sure the dot comes after the @ (so "a.b@c" or "@.com" don't pass):

var at = mail.indexOf('@');
var dotAfter = mail.indexOf('.', at + 2); // look for '.' after the '@'
if (at > 0 && dotAfter > at + 1) { /* accept */ }

Notes and next steps: simple presence checks are naive — they miss many invalid addresses and can accept invalid ones. For robust client-side validation use a proper email regex or the HTML5 type="email" input and always validate again on the server. See the docs for String.search and regex behavior (MDN search), and for indexOf compatibility (MDN indexOf) and input type="email" (MDN input email).

Recommended Answers

All 3 Replies

Member Avatar for Member #120589

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.