2013-09-27 103 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 
      }) 
     });