Home > OS >  email validation is not working in javascript?
email validation is not working in javascript?

Time:09-02

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 >
    <input type="text" placeholder="Email Address" id="email">
    <img src="/images/icon-error.svg" alt="" >
    <button type="submit"><img src="/images/icon-arrow.svg " ></button>

    <div >
      <small>please provide a valid Email</small>
    </div>
  </div>
</form>

CodePudding user response:

To create a regex use

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

you have created only a string, and there is no test method on string

CodePudding user response:

such as

var reg= /^\w @[a-zA-Z_] ?\.[a-zA-Z]{2,3}$/;
var result= reg.test("[email protected]");
console.log(result)
// VM1103:3 true

CodePudding user response:

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

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

  • Related