0

I'm writing a JS function that prompts the user to enter an email address. I want to confirm that the user input is an email address by checking if an '@' sign exists within the input. Then I want to return the email address if it's true.

My python knowledge has me writing this line, "if at == true return email", but the console is returning a syntax error. Any ideas? Code below:

function email_of_user() {
        var email = prompt("What is your email?");
        var at = email.indexOf("@");
            if at === true return email
      } 

PS. This is code is within an HTML doc, rather than a standalone JS file.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
nick_rinaldi
  • 641
  • 6
  • 17
  • Does this answer your question? [How to validate an email address in JavaScript](https://stackoverflow.com/questions/46155/how-to-validate-an-email-address-in-javascript) – Tristan Dec 03 '19 at 23:58
  • 1
    Does this answer your question? [How to validate an email address in JavaScript](https://stackoverflow.com/questions/46155/how-to-validate-an-email-address-in-javascript) – Triby Dec 04 '19 at 00:01
  • Not in particular, all I want is for the function to check if "@"exists within the prompted input, and if it does, return that email. I have literally started JavaScript 2 days ago so my question is meant to be naive. – nick_rinaldi Dec 04 '19 at 00:03

2 Answers2

1

To check if the email contains the '@' symbol you just need to be sure at is not -1

So that function might look something like:

function email_of_user() {
    var email = prompt("What is your email?");
    var at = email.indexOf("@");
    if (at !== -1) { return email };
} 

Careful, this could still return invalid emails. As someone commented, you might want to use regex like in this similar post

  • Thank you, this is the answer I was hoping for. I won't make a habit of doing it like this, in the future when developing I will make sure to use regex for any professional endeavor. This is just a test. – nick_rinaldi Dec 04 '19 at 00:06
1

The line of

if at === true return email

is incorrect, because you need to enclose the condition of the if into paranthesis, like

if (at === true) return email
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175