-2

I want to varify if the entered string is in email format or not. I am bit confused. I tried to write below code but failed. Can ayone help me please.

Javascript Code:
<script>
            function emailValidation(id)
            {
        var emailPattern =  var emailPattern = /^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
                if (emailPattern.test(id) === false)
                {
                    alert("not a valid email address.");
                 }            
                 document.getElementById(id).value = "";
            }
         </script>

HTML Code:
             <input type="text" id="empemail" onblur="emailValidation('empemail')" name="email" placeholder="eg: aaa@abc.ca" required="">

4 Answers4

1

You can also use HTML5 to validate your email input field by changing the type to email:

<input type="email" name="email">

If you don't want to use HTML5 and rely on javascript, you can use this thread as @springrolls suggested. You also have an error in your javascript code:

var emailPattern =  var emailPattern =  ...

And you are also not passing the value from the input field correctly. That's why your function is always returning false. Try this jsfiddle:

function emailValidation(id)
{
    var emailPattern = /^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
    var email = document.getElementById(id).value
    if (emailPattern.test(email) === false)
    {
        alert("not a valid email address.");
    }            
}

Also, don't forget to also check the email input server side. If you are using PHP, you can use something like this:

$email = $_POST["email"];
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $error = "Invalid email format"; 
}
Community
  • 1
  • 1
Laurens
  • 2,596
  • 11
  • 21
0

Try this pattern.

var emailPattern = /[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/i;

You can test the pattern with https://regex101.com/

Sergi Case
  • 226
  • 2
  • 12
  • – user3250190 Apr 27 '16 at 09:03
0

You can also use HTML5 validation by adding type="email" to the input field Example:

<!DOCTYPE HTML>
<html>
<head>
<title>Test Email Submit</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
  <form action="/submitForm">
   Email:<br>
  <input type="email" name="email"><br>
  <input type="submit" value="Submit">
  </form>
</body>
</html>
0
function isValidEmail(email) {
   var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
   if (!filter.test(email)) {
       return false;
    }
return true;
}

If Email is valid then it return true otherwise it return false

Prashant Gurav
  • 505
  • 7
  • 17