Match an email with RegEx

Posted on July 7, 2019

Here the pattern I use to validate an email in a text input field:

/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/g

Suppose to have this little component:

<input type="email" value="" id="email" />

and the javscript for the validation:

document.querySelector('#email').onblur = () => {

  var val = document.querySelector('#email').value
  var reg = val.match(/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/g)
  if(reg){
    console.log("it's valid, proceed")
  }else{
    console.log("nope, not valid")
  }

}

Here a pen.