Stephanie Brandon
Stephanie Brandon

Reputation: 15

I can't get my if and else if statement to work

I am trying to prompt the user to input a proper email if not correctly typed but can't get it to work. Thank you!

      function subscriptiton() {
        let name = prompt("What is your name?");
        let email = prompt("What is your email address?");

        if (typeof email === "string") {
          alert(
            "Thank you " +
              name +
              "! We will be in touch via email, meanwhile remember bees are our friends!"
          );
        } else if (typeof email === "number") {
          alert("Please enter valid email address.😉");
        }
      }

      let emailList = document.querySelector("button");
      emailList.addEventListener("click", subscriptiton);
    </script>

Upvotes: -1

Views: 57

Answers (3)

Pedro Coelho
Pedro Coelho

Reputation: 1617

The else if condition will never be satisfied since prompt function's return should be a string value (given a valid input), even if the input value is numeric. In any case, as you want to validate an e-mail, I would suggest the code below:

function subscriptiton() {    
    let name = prompt("What is your name?");
    let email = prompt("What is your email address?");

    if(validateEmail(email)) {
        alert("Thank you " + name + "! We will be in touch via email, meanwhile remember bees are our friends!");
    } else {
        alert("Please enter valid email address.😉");
    }
}
let emailList = document.querySelector("button");
emailList.addEventListener("click", subscriptiton);

function validateEmail(email) {
    const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(String(email).toLowerCase());
}

Upvotes: 1

yochanan sheinberger
yochanan sheinberger

Reputation: 735

try this:

function subscriptiton() {
  let name = prompt("What is your name?");
  let email = prompt("What is your email address?");
      
  if (isNaN(email)) {
    alert(
         "Thank you " +
              name +
              "! We will be in touch via email, meanwhile remember bees are our friends!"
          );
  } else {
    alert("Please enter valid email address.😉");
  }
} 

Upvotes: 1

Yanb
Yanb

Reputation: 700

The returned type of the prompt function is a String (only if it is not cancelled), so this code will always go to the typeof email === "string" branch.

Try some another way of doing it, if you want to check if a string is a number. Edit: and if you want to check if a email is valid, you can use a regex, an excellent way to do it.

Upvotes: 2

Related Questions