0

I'm trying to validate email such as a.b@c.d or a@b.c using JavaScript. And also it want to show the number of the character of the email like

Email: abc@gmail.com
atpos =3
dotpos =9

Here is my code:

<script>
function validemail() 
{
  var emailID = document.getElementById("email").value;
  var mailformat = /^([A-Za-z0-9\.])+\@([A-Za-z0-9])+\.([A-Za-z]{2,4})$/;
  atpos = emailID.indexOf("@");
  dotpos = emailID.lastIndexOf(".");
  if (mailformat.test(emailID))
      alert("Valid Email");
     document.write("atpos =", atpos, "<br/>");
     document.write("dotpos =", dotpos);
  else
      alert("Invalid Email, Try Again");
}
</script>
<html>
<body>
<div class="form"> 
<label for="email">Enter Email: </label> 
<input type = "text" id = "email"> 
<button onclick="validemail()" type="button">Submit</button>
</div>
</body>
</html>
DuDu
  • 59
  • 7

1 Answers1

-1

If you want to show the number of characters before and after @ you can simply use the split function like this

const emailID = document.getElementById("email").value;
const res = emailID.split(/[@]/);
const atpos = res[0].length;
const dotpos = res[1].length;

And for validation checkout this one: How can I validate an email address in JavaScript?

deadMan
  • 11
  • 3