0

我有以下一段代码。我需要在他提交表单时检查用户输入(他的电子邮件地址)的验证。如果电子邮件地址的格式不正确,则应显示错误消息。

问题是当我在文本框中输入错误的电子邮件地址并按下提交按钮时,没有任何反应。我曾经使用警报(我写的alert("Email"))检查代码并理解它$("#customerEmail").val()不返回任何值,而我目前在文本框中输入了一个值。可能是什么问题呢?

<form method="post" action="">
     <input type="text" id="customerEmail"/>
     <br/>
     <input type="submit" id="customerRegister" name="customerRegister"/>
</form>

<?php
  if(isset($_POST['customerRegister'])){
     echo'
    <script type="text/javascript" src="Scripts/jquery-1.10.2.min.js"></script>
    <script type="text/javascript">
       var EMail=$("#customerEmail").val();
       alert(Email);
       var atpos = EMail.indexOf("@");
       var dotpos = EMail.lastIndexOf(".");
           if (EMail != "")
       {
           if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= EMail.length) 
               {
                   $("#customerEmailSpan").html("wrong email address");
               }
           else if (atpos >= 1 && dotpos >= atpos + 2 && dotpos + 2 < EMail.length)
               document.getElementById("customerEmailSpan").innerHTML = "";
       }
    </script>';
    }
?>
4

1 回答 1

0

你为什么不做这样的事情而不是将 js 与 php 混合?

制作一个单独的 javascript 文件并将 js 代码放在这里。

您正在声明电子邮件并提醒电子邮件。这可能是一个原因。

(function($){

   //Call the script after document is loaded.
   $(document).ready(function() { 

      //on click event of submit button
      $("body").on("click", "#customerRegister", function(e){

       var EMail = $("#customerEmail").val();

       //This is the mistake you were doing. ie; print Email instead of EMail.
       alert(EMail);
       var atpos = EMail.indexOf("@");
       var dotpos = EMail.lastIndexOf(".");
           if (EMail != "")
       {
           if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= EMail.length) 
               {
                   $("#customerEmailSpan").html("wrong email address");
               }
           else if (atpos >= 1 && dotpos >= atpos + 2 && dotpos + 2 < EMail.length)
               $("#customerEmailSpan").val("");
       }


       });
    });

      }(jQuery));
于 2013-08-13T13:22:25.563 回答