电子邮件验证html和javascript

时间:2014-04-15 09:09:41

标签: javascript html html5 xhtml email-validation

下面是我的代码,主要用于"电子邮件验证"但由于某些原因它不能正常工作我不明白为什么,所以你介意看看吧。感谢

我认为主要问题在于document.getElementById("custEmail").onchange = chkEmail;因为某种原因导致chkEmail出现问题......以及搜索部分myEmail.value.search(+@[a-zA-Z_]+?.[a-zA-

    <html  xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Web Assignment 1 :Online shopping form</title>


<script type = "text/javascript">



      function chkEmail() {
        var myEmail = document.getElementById("custEmail");


        var pos = myEmail.value.search(+@[a-zA-Z_]+?.[a-zA-Z]{2,6});

        if (pos != 0) {
          alert("The email you entered (" + myEmail.value + 
                ") is not in the correct form. \n" +
                "The correct form is: " +
                "whatever@whatever.xxx\n" +
"Please fix it");
          myEmail.focus();
          myEmail.select();
          return false;
        } else
          return true;
      }


    </script>
</head>
<body>
<h1> Please fill in the information below </h1>

<form action="" 
>
<p>
<h2> Contact Info...</h2>
<pre>
     Last  Name     :  <input type="text" name="name2" size="20">
     Email          :  <input type="email" id = "custEmail" onchange ="chkEmail();" size="30">
     Mobile number  :  <input type="text" name="mob" size="15">
    </pre>
 <input type = "reset"  id = "reset" />
<input type = "submit"  id = "submit" />
  </p>

 </form>
 <script type = "text/javascript">
      <!--
// Set form element object properties to their 
// corresponding event handler functions

        document.getElementById("custEmail").onchange = chkEmail;
      // -->
    </script>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

如果您只想进行客户端验证,为什么不简单地使用HTML正则表达式进行验证,如下所示: 如果您只想进行客户端验证,为什么不简单地使用HTML正则表达式进行验证,如下所示:

<form action="">
<p>
<h2> Contact Info...</h2>
<pre>
    Last  Name     :  <input type="text" name="name2" size="20">
    Email          :  <input type="email" id = "custEmail" size="30" pattern="[^@]+@[^@]+\.[a-zA-Z]{2,6}">
    Mobile number  :  <input type="text" name="mob" size="15">
</pre>
<input type = "reset"  id = "reset" />
<input type = "submit"  id = "submit" />
</form>

请看这里的小提琴: http://jsfiddle.net/9gthN/

相关问题