Search code examples
javascripthtmlemail-validation

email validation is not working in javascript?


I have for a frontendmentorchallenge tried to do email validation for webpage. I have made a validation function to display error message when there is wrong email id entered. But it isn't working. I have given the html and JavaScript

function validate() {
  var email = document.getElementById("email").value;
  var reg = "^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$";
  var result = reg.test(email);

  if (result == false) {
    alert("sorry");
    return false;
  }
  return true;
}
<form action="#" method="post" onsubmit="return validate()">
  <div class="inputgrp">
    <input type="text" placeholder="Email Address" id="email">
    <img src="/images/icon-error.svg" alt="" class="error">
    <button type="submit"><img src="/images/icon-arrow.svg " ></button>

    <div class="errormsg">
      <small>please provide a valid Email</small>
    </div>
  </div>
</form>


Solution

  • My problem has been resolved. The problem is i created a string instead of creating RegExp.

    So i changed var reg = "^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$"; to the correct format as:

    var reg = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
    

    Thanks for those who answered my question. I posting this answer because in future it might be helpful to somebody.