0

I am trying to make an email validator and I want to make a command to check that the user input (the email the user enters) contains ONLY ONE OF "@" and ".". Example: name@@.com would be invalid

function validateEmail(){
let enterEmail = prompt("Enter your email to see if it is valid");
let removeSpace = (enterEmail.trim());
let s = removeSpace.indexOf('@');
let lastS = removeSpace.lastIndexOf('.');
if (s > 1 && lastS > 1) {
    Output("emailOutput", "The Email you have entered is valid");
    }
else {
    Output("emailOutput", "The Email you have entered is invalid");
}   
}
Michael Kheong
  • 194
  • 1
  • 10
  • 2
    Possible duplicate of [How to validate an email address in JavaScript?](https://stackoverflow.com/questions/46155/how-to-validate-an-email-address-in-javascript) – Artem Arkhipov May 30 '19 at 11:57
  • 2
    Just match to a regex. Note that it's perfectly OK for a valid email address to have more than one "." in it, so restricting that character would be a bad idea. Really it's better to not try much beyond "stuff@stuff" because email address syntax is extremely complicated, and even a syntactically-correct address could be completely wrong. – Pointy May 30 '19 at 11:57
  • 2
    I agree with @Pointy - I've seen and *experienced* people validating emails wrong way too many times. One of the most common ones that personally affects me is making `+` invalid, which it isn't. But way too often people deny the possibility to type `'` so people like O'Brien are excluded from registering. `.+@.+\..+` should be enough to cover the validity of email. And even then should probably just throw a warning, not stop you submitting, since an email of the format `email@localdomain` is *valid*. – VLAZ May 30 '19 at 12:02
  • 1
    If you are trying to ensure that an email is correct, just send the user a confirmation email with the provided email. For the rest, html5 also has email as a type, so there is really no need to validate it manually – Icepickle May 30 '19 at 12:03

3 Answers3

2

I recognise this is not what you are asking (and may not be relevant) but in-browser validation of an email address is achievable via:

<input type="email" />

which degrades gracefully to

<input type="text" />
Rounin
  • 27,134
  • 9
  • 83
  • 108
1
let s = "mail@@@.com"
s.match(/@/g).length 

Length here will be the number of occurrences in the string

Konstantin
  • 129
  • 4
  • 16
1

you can use:

const isEmailValid = (email) => {
    const isValid = /\S+@\S+\.\S+/.test(email);
    return isValid;
}
Isan Rivkin
  • 177
  • 1
  • 15