Search code examples
javascriptvalidationemailinputonblur

Email input instant validation with javascript


I'm trying to validate input type="email" with js.

I found different ways to do that but non of them works form me.

HTML

<label for="email" class="form__label">User e-mail:</label>
<input type="email" name="email" id="email" onblur="checkEmail(this.value);" class="form__input" >

JS

  document.addEventListener('DOMContentLoaded', function() {

  var email = document.getElementById('email');

  function checkEmail(email) {
    var reg1 = /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$/;

    if (reg1.test(email) == false) {
      email.style.border = "1px solid red";
    }else (reg1.test(email) == true) {
      email.style.border = "1px solid green";
    }
  };

});

What I get every time is:

Uncaught ReferenceError: checkEmail is not defined at HTMLInputElement.onblur ...

I know, I make some simple error but I'm struggling with this for a while now and can't move on...


Solution

  • You could ineed use the Email Check of HTML5 as quoted by @Andriy Klitsuk. So you could completely omit your extra checkEmail call.

    But getting to your error :

    Uncaught ReferenceError: checkEmail is not defined at HTMLInputElement.onblur

    you get the above error as the checkEmail function is present inside EventHandler document.addEventListener('DOMContentLoaded', function(){ .... and hence is not available outside it.

    You could take the function out of the EventListener as it is not being called inside the EventHandler anyway :

      document.addEventListener('DOMContentLoaded', function() {
    
      var email = document.getElementById('email');
      });
      function checkEmail(email) {
        var reg1 = /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$/;
    
        if (reg1.test(email) == false) {
          email.style.border = "1px solid red";
        } else if (reg1.test(email) == true) { // if was missing here
          email.style.border = "1px solid green";
        }
      };