Search code examples
javascriptclient-sideemail-validation

Email validation client side


<form action="#" method="post" id="book-list">
 <div class="form-group">
   <label for="email">Email</label>
   <input type="text" id="email" class="form-control">
 </div>
 <input type="submit" value="Add" class="btn btn-primary btn-block">
</form>
<script type="text/javascript">
 function isEmail(email){
    return /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z](2,4))$/.test(email);
    }   
 const form = document.querySelector('#book-list').addEventListener('submit',(e) =>{
    e.preventDefault();
    const inputEmail = document.querySelector('#email').value;
    if(isEmail(inputEmail) === false ){
      console.log('you lost');
      document.querySelector('#email').focus();
      return false;
    }else{
      console.log('you win');
      return true
    }

});
</script>

Playing around with this email validation, is there anything wrong with the code? even I filled the field with the proper email address like [email protected] it kept printing you lost result instead of printing the you win, is it because the form submit?


Solution

  • You can use input type='email' if you want to allow html5 to do the validation for you, the submit wont fire if the field is not valid.

    Otherwise you can change your regexp a bit to the below one

    ([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})