1

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>

6
  • 1
    I for one cannot email you. My email has 4 chars at the end. Change your quotes to / in the reg and remove the 3 so I also can email you: var reg = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,}$/; Commented Sep 1, 2022 at 10:58
  • that reg is a string and not a regexp Commented Sep 1, 2022 at 10:59
  • 1
    One problem is that var reg= "^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$"; does not create a regex, but a string. To create a regex use this: var reg= /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/; Commented Sep 1, 2022 at 11:00
  • 2
    Why not just use the email type: <input type="email" required />, and have the validation done for you? Commented Sep 1, 2022 at 11:08
  • @Andy It is for a challenge. I have added his link back Commented Sep 1, 2022 at 11:37

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

3

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.

1 Comment

It won't work with domains like 123abc . com, the [a-zA-Z_] rules restrict the domain name
-1

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

1 Comment

1. Please do not answer typo-type trivial questions that will have the answers in the comment to the question. 2. Please comment your answer with what you changed and why

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.