2013-03-13 82 views
0

我使用查詢驗證來驗證用戶在發送郵件之前填寫了所有文本字段。這是我的HTML表單:jQuery驗證問題非常困惑

<form class="email-form" action="php/email.php" method="POST" id="emailForm"> <br /> 
      <input type="text" class="required" placeholder="Your Name" /> <br /> 
      <input type="text" class="required" placeholder="Your Email" /> <br /> 
      <input type="text" class="required" placeholder="Subject" /><br /> 
      <textarea rows="10" class="required" ></textarea><br /> 
      <input type="submit" class="btn btn-primary required" /> 
</form> 

而且我的jQuery:

$(function() { 
    $('#emailForm').validate(); 
}); 

我然後訪問page並提交表單,而不輸入查詢的任何文字,只有第一個文本框被連接到它的錯誤信息。如果填寫了第一個文本框,表單將無任何問題提交。有人可以幫我嗎?謝謝

+0

驗證器設置代碼的其餘部分在哪裏? – 2013-03-13 03:13:20

+1

JQuery插件的驗證配置代碼在哪裏? – 2013-03-13 03:14:33

+0

驗證腳本通過'head.php'包含。上面的jQuery代碼位於聯繫頁面頂部 – 2013-03-13 03:18:52

回答

3

每個輸入必須包含一個name屬性或jQuery驗證插件將無法正常工作。

否則,在每個元素中使用class="required"沒有任何問題。

試試這個:

HTML

<form class="email-form" action="php/email.php" method="POST" id="emailForm"> <br /> 
    <input type="text" name="yourname" class="required" placeholder="Your Name" /> <br /> 
    <input type="text" name="youremail" class="required" placeholder="Your Email" /> <br /> 
    <input type="text" name="subject" class="required" placeholder="Subject" /><br /> 
    <textarea rows="10" name="description" class="required" ></textarea><br /> 
    <input type="submit" class="btn btn-primary required" /> 
</form> 

jQuery的

$(function() { 
    $('#emailForm').validate(); 
}); 

工作演示:http://jsfiddle.net/xSwfD/

+0

謝謝!我不知道一個名字是必需的,才能使它工作。剛剛還沒有到處添加名稱。 – 2013-03-13 05:26:55

1

刪除第一個class=required,看看會發生什麼?該表格現在將通過電子郵件進行驗證。做到這一點的方法是在html中提供一個唯一的名稱。我喜歡這種方式,因爲它提供了更多的靈活性,以進一步自定義:

<form class="email-form" action="php/email.php" method="POST" id="emailForm"> <br /> 
    <input type="text" name="name" placeholder="Your Name" /> <br /> 
    <input type="text" name="email" placeholder="Your Email" /> <br /> 
    <input type="text" name="subject" placeholder="Subject" /><br /> 
    <textarea rows="10" class="required small" ></textarea><br /> 
    <input type="submit" class="btn btn-primary" /> 
</form> 
$(function() { 

    $('#emailForm').validate({ 
      rules: { 
        name: "required", 
        email: "required", 
        subject: "required", 
      } 
    }); 

}); 

使用這個,你可以使用郵件等領域獲得各種花式。看到這個好tutorial

Fiddle我正在玩耍。

+0

在每個元素中使用'class =「required」'沒有任何問題。代碼因爲缺少'name'屬性而被破壞。 – Sparky 2013-03-13 04:18:15