Search code examples
javascriptemail-validation

JS Student Email Validation


I am a beginner in Javascript and am looking to find a solution to why the code below is not working.
I've reviewed several tutorials here on StackOverflow and believe it should work... but it's not.

The HTML looks like this:

<form id="personalInfo"> 
    <h2>Email: </h2>
    <input type="text" name="Email" id="Email">
    <br>
</form> 

<input type="button" onclick = "validateEmail()">

The Javascript looks like this:

function validateEmail() 
{
    var reg = /^([A-Za-z0-9_\-\.]){1,}\@([A-Za-z0-9_\-\.]){1,}\.([A-Za-z]{2,4})$/;
    var address = document.forms[personalInfo].elements[Email].value;

    if (reg.test(address) == false) {
        alert ("Email not valid");
        return false;
    }
    return true;
}

By my accounts, this should pop up an alert if the email address entered by the user is not valid.
Instead, nothing happens at all. I'm not sure if the test is even run.


Solution

  • function validateEmail() {
      // There are, I feel, better version of this regex online
      // You can check "https://emailregex.com/"
      var reg = /^([A-Za-z0-9_\-\.]){1,}\@([A-Za-z0-9_\-\.]){1,}\.([A-Za-z]{2,4})$/;
    
      // document.getElementById() - Easier to read & understand, and more widely used
      var address = document.getElementById('Email').value;
    
      // Corrected your returns - not the main issue in the function, but the old
      // returns might have caused confusion
      if (reg.test(address) == false) {
        alert("Email not valid");
        return false
      }
      return true
    }
    <form id="personalInfo">
      <h2>Email: </h2>
      <input type="text" name="Email" id="Email">
    </form>
    
    <!-- You had a typo on the onclick but has since been fixed -->
    <input type="button" onclick="validateEmail()" value="Submit">