0

I have this sample:

link

CODE HTML:

<input type="text" name="email" class="email" placeholder="Your email address">

CODE JS:

$(document).ready(function ($) {
      function validateEmail(email) {
                var re = /\S+@\S+\.\S+/;
                  return re.test(email);
      }

      var email = $(".email").val();
      if (validateEmail(email)) {
        alert("correct format");
      }else{
        alert("icorrect format");
      }
});

Code validation above does not work properly.

Can you tell me please what is the problem? Any data is entered in the input does not check properly

Thanks in advance!

Cristi
  • 531
  • 1
  • 8
  • 21
  • look at this https://regex101.com/ got snippets, sure there is one for email https://regex101.com/library?filterFlavors=javascript – Álvaro Touzón Aug 04 '17 at 07:01
  • May be https://stackoverflow.com/questions/7635533/validate-email-address-textbox-using-javascript – Rohit Sharma Aug 04 '17 at 07:01
  • /^(([a-zA-Z0-9]+)|([a-zA-Z0-9]+((?:\_[a-zA-Z0-9]+)|(?:\.[a-zA-Z0-9]+))*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-zA-Z]{2,6}(?:\.[a-zA-Z]{2})?)$)/ Use this regex –  Aug 04 '17 at 07:02

4 Answers4

1

$(document).ready(function($) {
  function validateEmail(email) {
    var re = /^(([a-zA-Z0-9]+)|([a-zA-Z0-9]+((?:\_[a-zA-Z0-9]+)|(?:\.[a-zA-Z0-9]+))*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-zA-Z]{2,6}(?:\.[a-zA-Z]{2})?)$)/;
    return re.test(email);
  }

  var email = $(".email").val();
  if (validateEmail(email)) {
    console.log("correct format");
  } else {
    console.log("icorrect format");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<input type="text" name="email" class="email" value="abc.def@gmail.com" placeholder="Your email address">

Check this above snippet.

1

$(function(){

$('#txtEmail').on('input', function () {
    console.log(validateEmail($(this).val()));
})
})

function validateEmail(email) {
    var expr = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
    return expr.test(email);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="txtEmail" type="text" name="email" class="email" placeholder="Your email address">

try this one.... type email it's return true otherwise it return false.

0

If you want simple and built-in check. I would recommend type="email". However, beware that this is not fully supported everywhere. More info here

Tree Nguyen
  • 1,198
  • 1
  • 14
  • 37
0

Why dont just use <input type="email" name="email">? It can validate too.

ron
  • 175
  • 3
  • 14