2013-09-27 41 views
0

我有很多形式,創造了jQuery驗證()

我有這樣的HTML

<form method="post" id="form_commento-[i]" class="form_fancybox_commenti"> 
    <div class="form-section"> 
     <span style="position: relative"> 
      <input type="text" id="commento_form_[i]_commento" name="commento_form_[i][commento]" required="required"/> 
      <button type="submit" class="submit-button" id="submit_form_commenti">Commenta</button> 
     </span> 
    </div> 
</form> 

在哪裏[i]是指數

在我的文檔準備好我有

$(document).ready(function() { 

    jQuery.validator.addMethod("alphanumeric", function (value, element) { 
     return this.optional(element) || /^[a-zA-Z0-9\n\-'àèìòù: <_,. !?()]*$/.test(value); 
    }, "error"); 

    $('.form_fancybox_commenti').each(function(index, numero_form) { 

    var theRules = {}; 

    theRules[ 
     'commento_form_['+index+'][commento]'] = {alphanumeric: true}; 


    $(this).validate({ 
     rules: theRules, 
     submitHandler: function(form) { 
      save(form); 
     } 
    }); 
}); 

但我的自定義規則不起作用。

無論如何要解決這個問題?

+0

什麼是您的JavaScript控制檯告訴你嗎? – Sparky

回答

1

如果namecommento_form_[i][commento],那麼你就錯過了一組在這裏括號...

'commento_form_'+index+'[commento]' 

=>

'commento_form_['+index+'][commento]' 

然而,在這一點上,你還沒有定義index因此,此方法會因JavaScript控制檯錯誤而失敗。


這段JavaScript有一個非常簡單的替代方案。添加class="alphanumeric"<input>元素,你的代碼是簡單地減少到這一點:

$(document).ready(function() { 

    jQuery.validator.addMethod("alphanumeric", function (value, element) { 
     return this.optional(element) || /^[a-zA-Z0-9\n\-'àèìòù: <_,. !?()]*$/.test(value); 
    }, "error"); 

    $('.form_fancybox_commenti').each(function (index, numero_form) { 
     $(this).validate({ 
      submitHandler: function (form) { 
       save(form); 
       // alert('save form: ' + index); // for demo 
       return false; // blocks default form action 
      } 
     }); 
    }); 

}); 

DEMO:http://jsfiddle.net/XTtTP/


如果你寧願使用JavaScript來分配你的規則,你也可以在jQuery .each()中使用the .rules('add') method,如下所示,並且不需要索引:

$('input[name^="commento_form_"]').each(function() { 
    $(this).rules('add', { 
     alphanumeric: true 
    }); 
}); 

DEMO:http://jsfiddle.net/T776Z/


BTW,已經有一個方法叫the additional-methods.js filealphanumeric。請參閱:http://jsfiddle.net/h45Da/

+0

非常感謝。我使用$(「#commento_form _ [」+ index +「] _ commento」)。addClass(「alphanumeric」);在每個 – Barno

+0

我想字母數字與一些特殊字符。再次感謝 – Barno

0

這是我找到了最好的解決方案和我'目前使用在我的項目:

 // Adding rule to each item in commento_form_i list 
     jQuery('[id^=commento_form_]').each(function(e) { 
     jQuery(this).rules('add', { 
      minlength: 2, 
      required: true 
      }) 
     });