Alert if email is valid or invalid

Hello. I am trying to have someone enter an email address and if it’s invalid, it prompts that it’s an invalid email address. I have my code here and it keeps saying “Uncaught TypeError: Cannot read properties of undefined (reading ‘match’) at ValidateEmail”

'use strict'
///listen to 29:35 in voice notes!!! ///

/* Add a function to get the current date and time.
Write the date on the page in a user friendly format */


// Create function to capitalize first char of firstName variable //
const capFirstChar = (str) => str.charAt(0).toUpperCase() + str.slice(1);

// Get user's name //
const firstName = prompt('What is your name?');



// Switch statement to get time of day //
const currTime = new Date();
currTime.getHours();
const currHour = currTime.getHours();
switch (true) {
    case (currHour < 12):
        document.getElementById('greeting').innerHTML = `Good morning, ${capFirstChar(firstName)}!`;
        console.log("Good morning!");
        break;
    case (currHour > 12 && currHour < 17):
        document.getElementById('greeting').innerHTML = `Good afternoon, ${capFirstChar(firstName)}!`;
        console.log("Good afternoon!");
        break;
    default:
        document.getElementById('greeting').innerHTML = `Good evening, ${capFirstChar(firstName)}!`;
        console.log("Good evening!");
        break;
};

const userEmail = 'email@email.com';
const emailSplit = userEmail.split('@');
console.log(emailSplit);
const var1 = userEmail.split([0]);
const var2 = userEmail.split([1]);
console.log(var1)
console.log(var2)

//Function to validate email //

// function validEmail(email) {
//     const emailRegex = /[-\w.]+@([A-z0-9][-A-z0-9]+\.)+[A-z]{2,4}/;
//     const valid = email.match(emailRegex);
//     return valid;
// };

function ValidateEmail(input) {

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

    if (input.value.match(validRegex)) {

        alert("Valid email address!");

        document.form1.text1.focus();

        return true;

    } else {

        alert("Invalid email address!");

        document.form1.text1.focus();

        return false;

    }


}
let testEmail = prompt('What is your email?');
ValidateEmail(testEmail);
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <link rel="stylesheet" href="trivia.css">
    <title>Trivia Game!</title>
</head>

<body>
    <header>
        <p id="greeting"></p>
        <h1>Trivia Game!</h1>
        <!-- <p class="between">(Between 1 and 20)</p> -->
        <button class="btn again">Again!</button>
        <div class="number">?</div>
    </header>
    <main>
        <section class="left">
            <input type="number" class="guess" />
            <button class="btn check">Check!</button>
        </section>
        <section class="right">
            <p class="message">Start guessing...</p>
            <p class="label-score">💯 Score: <span id="score">0</span></p>
            <p class="label-highscore">
                🥇 Highscore: <span id="highscore">0</span>
            </p>
        </section>
    </main>
    <script src="trivia.js"></script>
    <script>quiz();</script>

</body>

</html>

The first error I am getting with your code is:

“Uncaught TypeError: input.value is undefined”

This is referring to the following line in the ValidateEmail function:

 if (input.value.match(validRegex)) {

Are you sure that input.value is what you want here? I would add a console.log(input) at the beginning of that function to verify the value of input.

Hello there. Input is the parameter of the function. So whenever I call the function, I put in the variable of what the user was prompted, which was asking them to enter an email

This doesn’t create a form, it creates a prompt, but you are trying to access the value the user is entering into the prompt as if it was a form.

I tried changing it up a bit and found another code online here JavaScript : email validation - w3resource and tried to make it work, but I guess it won’t work? lol. I originally had this, but it failed miserably — kept looping. ):

//Function to validate email //

function validEmail(email) {
    const emailRegex = /[-\w.]+@([A-z0-9][-A-z0-9]+\.)+[A-z]{2,4}/;
    const valid = email.match(emailRegex);
    return valid;
};

const emailAddress = prompt('Please enter your email');
while (!validEmail(emailAddress)) {
    prompt('Please enter a valid email');
    // console.log('Please enter a valid email');
}

Figured it out!!!

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>JavaScript form validation - checking email</title>
    <link rel='stylesheet' href='form-style.css' type='text/css' />
</head>

<body onload='document.form1.text1.focus()'>
    <div class="mail">
        <h2>Input an email and Submit</h2>
        <form name="form1" action="#">
            <ul>
                <li><input type='text' name='text1' /></li>
                <li>&nbsp;</li>
                <li class="submit"><input type="submit" name="submit" value="Submit"
                        onclick="ValidateEmail(document.form1.text1)" /></li>
                <li>&nbsp;</li>
            </ul>
        </form>
    </div>
    <script src="email-validation.js"></script>
</body>

</html>
function ValidateEmail(inputText) {
    var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
    if (inputText.value.match(mailformat)) {
        document.form1.text1.focus();
        return true;
    }
    else {
        alert("You have entered an invalid email address!");
        document.form1.text1.focus();
        return false;
    }
}

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.