David de Lavign
David de Lavign

Reputation: 13

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?

Upvotes: 1

Views: 361

Answers (3)

James Oshomah
James Oshomah

Reputation: 224

Your regular expression in the function isEmail is not correct. Change it to this

function isEmail(email){
 return /^([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9_-]+)$/.test(email);
 } 

Then you will get the right response when you submit with a valid email.

Upvotes: 0

MKougiouris
MKougiouris

Reputation: 2861

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})

Upvotes: 1

thgaskell
thgaskell

Reputation: 13256

The problem with your regular expression is the syntax for 2 to 4 characters.

Instead of (2,4) it should be {2,4}

function isEmail(email){
    return /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/.test(email);
}

isEmail('[email protected]')
// true

However, you may want to just use HTML's built in email type for your input. This will probably be more reliable than any regular expression you could could craft.

Upvotes: 0

Related Questions