Validate Email bằng JavaScript – VietTuts

Chúng ta có thể xác thực email bằng JavaScript.

Có nhiều tiêu chí cần phải tuân theo để xác thực email như:

  • email phải chứa ký tự ‘@’ và ‘.’
  • Phải có ít nhất một ký tự trước và sau ‘@’
  • Phải có ít nhất hai ký tự sau ‘.’ (dấu chấm).

Nội dung chính

  • Ví dụ xác thực email bằng JavaScript

Ví dụ xác thực email bằng JavaScript

<script>
    function validatEemail() {
        var x = document.myform.email.value;
        var atposition = x.indexOf("@");
        var dotposition = x.lastIndexOf(".");
        if (atposition < 1 || dotposition < (atposition + 2)
                || (dotposition + 2) >= x.length) {
            alert("Please enter a valid e-mail address.");
            return false;
        }
    }
</script>
<body>
  <form name="myform" method="post" action="#" onsubmit="return validatEemail();">
    Email: <input type="text" name="email"><br> 
    <input type="submit" value="register">
  </form>

Kết quả: