2013-04-02 39 views
-1

我是Jquery驗證的新手(http://docs.jquery.com/Plugins/ValidationJquery驗證 - 如何驗證動態表單?

我有一個動態表單。我需要知道是否有可能驗證這樣的表單:

<form ...> 
<div class="multi-city">       
    <div class="controls visible"> 
     <label for="id_form-0-city_input">City</label> 
     <input type="text" name="form-0-city_input" class="city-input ui-autocomplete-input" id="id_form-0-city_input" autocomplete="off"> 
     <p style=""><a href="#" class="delete">Remove</a></p> 
    </div> 
    <input type="hidden" id="id_form-0-city" name="form-0-city"> 

    <div class="controls visible"> 
     <label for="id_form-1-city_input">City</label> 
     <input type="text" name="form-1-city_input" class="city-input ui-autocomplete-input" id="id_form-1-city_input" autocomplete="off"> 
     <p style=""><a href="#" class="delete">Remove</a></p> 
    </div> 
    <input type="hidden" id="id_form-1-city" name="form-1-city"> 

    <div class="controls hidden"> 
     <label for="id_form-2-city_input">City</label> 
     <input type="text" name="form-2-city_input" class="city-input ui-autocomplete-input" id="id_form-2-city_input" autocomplete="off"> 
     <p style=""><a href="#" class="delete">Remove</a></p> 
    </div>          
</div> 
</form> 

基本上我需要驗證「.controls.visible」。通過代碼:

$('.multi-city .controls.visible') 

我應該使用什麼策略來驗證這個動態字段?

任何想法?

最好的問候,

+0

[標籤:jQuery的驗證引擎]標籤是一個完全不同的插件。編輯。 – Sparky

回答

0

不完全知道你是問什麼。 默認,這個插件將簡單地忽略任何隱藏的字段。如果這些字段不是真正「隱藏」的,那麼當您創建或「刪除」(隱藏?)這些字段時,您需要動態編輯規則。做這樣的操作的唯一方法是使用已經內置到插件的方法...

  • rules('add')
  • rules('remove')

看到所有文件:http://docs.jquery.com/Plugins/Validation#Plugin_methods


要將規則添加到動態添加的字段中,您可以在創建字段後立即使用the rules('add') method

$('[name="Field2"]').rules('add', { 
    required:true, 
    messages: { 
     required: "Custom message." 
    } 
}); 

或者一次爲許多新的領域,使用 「開始以」 選擇和.each ...

$('[name^="Field"]').each(function() { 
    $(this).rules('add', { 
     required:true, 
     messages: { 
      required: "Custom message." 
     } 
    }); 
}); 

這種方法的簡單演示:http://jsfiddle.net/xCY4T/1/


另一種方式將創建 a class使用the addClassRules method

$.validator.addClassRules("MyRule", { 
    required: true 
}); 

然後,當你創建新的領域,確保他們每個都包含沿着class="MyRule"具有獨特name,當然。

<input type="text" name="Field1" class="MyRule" /> 
<input type="text" name="Field2" class="MyRule" /> 

這種方法很簡單,但我看不到默認消息。

簡單的演示:http://jsfiddle.net/xCY4T/3/