jQuery在jQuery.each()中验证

jQuery在jQuery.each()中验证,jquery,jquery-validate,Jquery,Jquery Validate,我有很多表格可以创建 我有这个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]_comment

我有很多表格可以创建

我有这个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);
        }
    });
});
$(文档).ready(函数(){
addMethod(“字母数字”,函数(值,元素){

返回此.optional(element)| |/^[a-zA-Z0-9\n\-'aèèù:如果
名称
commento_form|[i][commento]
,则此处缺少一组括号

'commento_form_'+index+'[commento]'
=>

但是,此时您还没有定义
索引
,因此此方法失败,并出现JavaScript控制台错误


有一个非常简单的替代JavaScript块的方法。将
class=“alphanumeric”
添加到
元素中,代码简化为:

$(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
            }
        });
    });

});
演示:



顺便说一句,中已经有一个名为字母数字的方法。请参阅:

这是我找到的最好的解决方案,我目前正在我的项目中使用:

        // 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
            })
        });

您的JavaScript控制台告诉您什么?非常感谢。我使用$(“#commento_form”[“+index+”]_commento”)。addClass(“字母数字”);在eachi希望字母数字带有一些特殊字符。再次感谢
$('input[name^="commento_form_"]').each(function () {
    $(this).rules('add', {
        alphanumeric: true
    });
});
        // 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
            })
        });