user46777
user46777

Reputation: 33

Regex requirement to have @ symbol only once in a string

I am new to javaScript and the problem I am facing is that I have to match the @ symbol and make sure it is allowed only once in a string. To do so I have written the following regex.

var regexpat=/[@]{1}/;
    if(regexpat.test(valu))
       testresults = true;
       else 
      {
            alert("Please input a valid email address!");
            testresults = false;
      }

My regex is working for the following input value: abcd@[email protected]. However, if I provide the input value as "abcd@"@abc.com it is not throwing the alert error message.

How can I change my regex so that it will work for "abcd@"@abc.com?

Upvotes: 3

Views: 1166

Answers (3)

Barmar
Barmar

Reputation: 780974

Your regexp just tests whether there's a single @ in the string, it doesn't reject more than one. Use:

var regexppat = /^[^@]+@[^@]+$/;

This matches an @ that's surrounded by characters that aren't @.

var valu;
var regexpat = /^[^@]+@[^@]+$/;

while (valu = prompt("Enter email")) {
  if (regexpat.test(valu))
    console.log(valu + " is valid");
  else {
    console.log(valu + " is invalid");
  }
}

Upvotes: 2

MattDiMu
MattDiMu

Reputation: 5013

E-Mail regex is much more, than just the occurence of just one @ character. This is the email-regex specified in the W3C Spec (e.g. used for <input type="email">):

/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/

Upvotes: 0

Ankit Agarwal
Ankit Agarwal

Reputation: 30739

The easy way could also be to use the split("@") for this:

var value = 'abcd@@';
 if(value.split("@").length === 2){
  testresults = true;
 }else{
   alert("Please input a valid email address!");
   testresults = false;
 }     
      

Just split your string with @ and since you require only one occurrence of @ there must be an array of length 2 so you can compare the array with length 2. If the array length is greater than 2 then there are more than one occurrence of @

Upvotes: 0

Related Questions