2013-08-27 107 views
1

我有3組相同的字段,這是三個不同成員的名字和姓氏。我正在嘗試驗證提交表單的字段。我附上了驗證碼,工作正常。同一個驗證多個字段

我的問題是,我的驗證代碼看起來如此手動,因爲我正在爲每個字段編寫代碼。有沒有辦法編寫單行代碼來驗證具有不同名稱屬性的相同類型的文本字段?

例如在我的頌名firstname1,firstname2,firstname3,firstname4,firstname5中,具有相同類型的驗證,因此我想在短行中爲這些字段編寫驗證碼,而不是編寫5行不同的行。

$().ready(function() { 
    $("#signupForm").validate({ 
     rules: { 
      firstname1: "required", 
      firstname2: "required", 
      firstname3: "required", 
      lastname1: "required", 
      lastname2: "required", 
      lastname3: "required", 

     },   
     messages: { 
      firstname1: "Please enter your firstname", 
      firstname2: "Please enter your firstname", 
      firstname3: "Please enter your firstname", 
      lastname1: "Please enter your lastname", 
      lastname2: "Please enter your lastname", 
      lastname3: "Please enter your lastname", 

     } 
    }); 
}); 

DEMO HERE

+0

它會出現在這個在真實的情景? –

+0

請看我的答案,如果它滿足你的需要:) – Roopendra

回答

2

Plase試試這個: -

$(document).ready(function(){ 
    $("#signupForm").validate(); 
    $("input[name^=firstname]").each(function() { 
     $(this).rules("add", { 
      required: true, 
      messages: { 
      required: "Please enter your firstname" 
      } 
      }); 
    }); 
    $("input[name^=lastname]").each(function() { 
     $(this).rules("add", { 
      required: true, 
      messages: { 
      required: "Please enter your lastname" 
      } 
      }); 
    }); 
}); 

工作小提琴: - http://jsfiddle.net/rw9ns/34/

+0

你可以檢查這個小提琴http://jsfiddle.net/rw9ns/35/。這是行不通的,當我結合我現有的代碼 – Sowmya

+0

嗨Sowmya,謝謝你的努力。你傳遞錯誤的ID。請參閱http://jsfiddle.net/rw9ns/36/。將您的jquery'registration'中的表單ID更改爲'signupForm'。 – Roopendra

+0

是的。你的代碼是正確的但不幸的是它仍然不起作用在我的頁面上。這裏是最後的小提琴http://jsfiddle.net/8JQrj/1/ PLease chk this,在這些文本字段是循環中,你可以通過點擊添加人按鈕生成它 – Sowmya