Waiting Answer October 15, 2024

Email Validation In Javascript Not Working

This is my JavaScript code to check email validation in Javascript. But it is not working. When I entered the wrong Email, my email validation code was successful. 

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

           if (res == false) {
                   alert("Failed");
           }else{
                   alert("success")
           }
          return true;
    }

    <form action="#" onsubmit="return validateEmailId()">
      <div class="inputgrp">
        <input type="text" placeholder="Email Address" id="email_id">
        
        <button type="submit">Submit</button>
      </div>
    </form>

Answers
2024-10-15 10:09:14

I think you created a string instead of creating RegExp.

Please change  

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

to

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

It will work. cheers..