-2

I am trying to make a client side validation to ensure an email is in the correct format using the .match() function, however I am having an issue which I can't seem to find the cause of. The error message won't hide when a correctly formatted email address is inputted.

HTML

    <form id="signupform">
         <label for="email">Email:</label>
         <input id="email" type="text"><br><br>
         <p class="error-msg" id="error-msg-invalid-email">Email is not Valid (Client Side Validation)</p>
    </form>

JavaScript

const signupform = document.getElementById("signupform");
const errorMsgInvalidEmail = document.getElementById("error-msg-invalid-email");

signupform.addEventListener('submit', (e) => {
        e.preventDefault();
        checkInputs();
});

function checkInputs () {
        const email = document.getElementById("email").value.trim();

        const regx = /^([a-zA-Z0-9\._]+)@([a-zA-Z0-9])+. ([a-z]+)(. [a-z]+)?$/;

        if(email.match(regx)) {
            errorMsgInvalidEmail.style.display = "none";
        }else{
            errorMsgInvalidEmail.style.display = "block";
        }
};

I have also tried using the .test() function and that also didn't seem to work. The changes are shown below.

if(regx.test(email)) {
      errorMsgInvalidEmail.style.display = "none";
      return true;
}else{
      errorMsgInvalidEmail.style.display = "block";
      return true;
}
  • Can you provide some examples of the emails that regex is meant to match? You appear to have spaces in there which is pretty unusual. – Andy Dec 13 '22 at 05:18
  • 1
    Attempting to use a single regex to match exactly what the RFC permits is usually ill-advised; many of the regexes you find online have glaring problems with perfectly valid addresses, and many will also allow invalid email addresses. See e.g https://stackoverflow.com/questions/201323/how-can-i-validate-an-email-address-using-a-regular-expression/201378#201378 for a discussion. – tripleee Dec 13 '22 at 05:38
  • It would be far easier to use [the email input element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email), and [client-side form validation](https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation). – Andy Dec 13 '22 at 05:52

3 Answers3

0

Try This:

    function checkInputs () {
            const email = document.getElementById("email").value.trim();
    
            const regx = /^[A-Za-z0-9._+\-\']+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}$/;
    
            if(email.match(regx)) {
                errorMsgInvalidEmail.style.display = "none";
            }else{
                errorMsgInvalidEmail.style.display = "block";
            }
    };
  • Permitting a dot or a dash immediately after `@` seems wrong. More fundamentally, this will reject addresses with subdomain parts, which are mandatory in many top-level country domains (`.co.uk`, `.com.au`, `.gov.pk`, etc etc) – tripleee Dec 13 '22 at 05:36
0

You've got an extra space in your regex after the period. Use:

const regx = /^([a-zA-Z0-9\._]+)@([a-zA-Z0-9])+.([a-z]+)(. [a-z]+)?$/;

It may help you to use a regex validator, like https://regex101.com/.

Cleaver
  • 11
  • 2
  • 2
    Even with the obvious flaws fixed, this will disqualify some valid email addresses, and of course, with the flaws, permit many invalid ones. – tripleee Dec 13 '22 at 05:34
  • 1
    @Cleaver Did you test your "fixed" regex on that validator? – gre_gor Dec 13 '22 at 05:41
  • 1
    Yes, I tested the regex with that validator and separately to confirm it worked. I agree this regex isn't the best solution for validating emails but I was aiming to keep it mostly unchanged from the original post and just solve the problem they presented! – Cleaver Dec 13 '22 at 05:45
  • [It's pretty bad](https://regex101.com/r/d8BaVb/1) – gre_gor Dec 13 '22 at 05:52
-1

Hi Mughil,

Thanks for your question.!!

I add some changes to your validate function, and the issue is a syntax and logic error.

function checkInputs() {
  const email = document.getElementById('email').value.trim();
  const regx = new RegExp(/[a-zA-Z0-9]+@[a-zA-Z]+\.[a-zA-Z]{2,3}/);
  const isMatch = regx.test(email);
  errorMsgInvalidEmail.style.display = isMatch ? 'none' : 'block';
}

For regex validation expression use the new RegExp() constructor, so you can use the .test() method, in this way you can validate against a Boolean value.


Demo with the change suggestion

const signupform = document.getElementById('signupform');
const errorMsgInvalidEmail = document.getElementById('error-msg-invalid-email');

errorMsgInvalidEmail.style.display = 'none';

signupform.addEventListener('submit', (e) => {
  e.preventDefault();
  checkInputs();
});

function checkInputs() {
  const email = document.getElementById('email').value.trim();
  const regx = new RegExp(/[a-zA-Z0-9]+@[a-zA-Z]+\.[a-zA-Z]{2,3}/);
  const isMatch = regx.test(email);
  errorMsgInvalidEmail.style.display = isMatch ? 'none' : 'block';
}
<div id="app">
  <form id="signupform">
    <label for="email">Email:</label>
    <input id="email" type="text"><br><br>
    <p class="error-msg" id="error-msg-invalid-email">Email is not Valid (Client Side Validation)</p>
  </form>
</div>

I you want to read some other answer about using regex for email address validation. You can take a look at this stackoverflow question How can I validate an email address in JavaScript?

Regards

boykland
  • 134
  • 10
  • I don't see how `RegExp` really improves anything. And that regex allow for a lot of invalid addresses ("[@test@test.com}@"). – gre_gor Dec 13 '22 at 06:18