How to validate an email using Jquery?

Dung Do Tien Apr 10 2020 75

I have a form Sign Up and I need to validate email valid format. I am using indexOf() of @ and dot. But I think it is not a good solution. I have research someone says use regex but I need a demo for you or any suggestion.

<div class="col-md-2">
    <div class="title">
      <h1> Sign Up </h1>
    </div>
    <div class="content-form">
         <div class="item"> 
            <input class="input" id="txtName" type="text" placeholder ="Username" />
         </div>
         <div class="item"> 
            <input class="input" id="txtPass" type="text" placeholder ="Password" />
         </div>
         <div class="item"> 
            <input class="input" id="txtEmail" type="text" placeholder ="Email" />
         </div>
    </div>
    <div class="button">
       <button type="submit">Submit</button>
    </button>
</div>
$("button").click(function(){
   var email = $("#txtEmail").val();
   if(email.indexOf(".") < 0 || email.indexOf("@") < 0){
      alert('Email is not valid ("ex : example@gmail.com")');
   }
});
Have 1 answer(s) found.
  • It's that right. I think use regex to validate email is a good solution. If you don't' know regex you can read more here. Below is a function help you validate an email :

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

    Explain pattern:
    ^ : Start with below
    ([a-zA-Z0-9_.+-]) : Contain text normal(a-z) or uppercasse(A-Z) or number(0-9) or shift minus or dot or plus or dash.
    +\@ : Contan one @
    (([a-zA-Z0-9-])+\.) : Contain text normal(a-z) or uppercasse(A-Z) or number(0-9) or plus and one dot(.).
    +([a-zA-Z0-9]{2,4}) : Contain from 2 to 4 characters text normal(a-z) or uppercasse(A-Z) or number(0-9).
     

    Use can store this function to common to reuseable and now to use this

    $("button").click(function(){
       var email = $("#txtEmail").val();
       if(!isEmail(email)){
          alert('Email is not valid ("ex : example@gmail.com")');
       }
    }); 

    I hope it helpful for you.

    Sandeep Kumar Apr 11 2020
Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips