jquery – Bootstrap formvalidation.io试图要求一个字段或其他

我最近购买并使用Bootstrap FormValidation从http://formvalidation.io/和使用示例在http://formvalidation.io/examples/requiring-at-least-one-field/我试图设置我的需要EITHER电子邮件或电话号码,但我不能得到的例子正常工作。无论我做什么,我只能在主电子邮件字段下看到一条错误消息“您必须至少输入一个联系方法”。

如果FULL代码将有所帮助,我可以发布,但这里是相关的代码段。

<div class="form-group">
    <label class="control-label" for="primaryEmail">Primary Email</label>
    <input type="text" class="form-control contactMethod" id="primaryEmail" 
                               name="primaryEmail" value="" placeholder="Enter email">
</div>
<div class="form-group">
    <label class="control-label" for="cPhone">Cell Phone</label>
    <input type="text" class="form-control contactMethod" id="cPhone" name="cPhone" 
            value="" placeholder="Enter cell phone">
</div>

javascript的验证部分

$('#form').formValidation({
            framework: 'bootstrap',
            icon: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields: {

                cPhone: {
                    validators: {
                        phone: {
                            country: 'country',
                            message: 'The value is not valid %s phone number'
                        }
                    }
                },
                primaryEmail: {
                    validators: {
                        emailAddress: {
                            message: 'The value is not a valid email address'
                        }
                    }
                },
                secondaryEmail: {
                    validators: {
                        emailAddress: {
                            message: 'The value is not a valid email address'
                        }
                    }
                },
                wPhone: {
                    validators: {
                        phone: {
                            country: 'country',
                            message: 'The value is not valid %s phone number'
                        }
                    }
                },
                contact : {
                    selector: '.contactMethod',
                    validators: {
                        callback: {
                            message: 'You must enter at least one contact method',
                            callback: function(value, validator, $field) {
                                var isEmpty = true,
                                // Get the list of fields
                                $fields = validator.getFieldElements('contact');
                                console.log($fields);
                                for (var i = 0; i < $fields.length; i++) {
                                    if ($fields.eq(i).val() !== '') {
                                        isEmpty = false;
                                        break;
                                    }
                                }

                                if (!isEmpty) {
              // Update the status of callback validator for all fields
              validator.updateStatus('contact', validator.STATUS_VALID, 'callback');
                                    return true;
                                }

                                return false;
                            }
                        }
                    }
                }
            }
        });

在例子中行$ fields = validator.getFieldElements(‘cm’);有cm替换为电子邮件,但它似乎只是一个任意标签。但它可能不是一个匹配validator.updateStatus(‘cm’,validator.STATUS_VALID,’callback’)的标签;线。 cm已更改为接触

所有其他验证似乎都在页面上工作。

更新:

如果我把$ fields转储到控制台$ fields = validator.getFieldElements(‘cm’);我得到“input =([name =”primaryEmail“])”我本来以为它会是一个对象与primaryEmail和cPhone。

更新5-18-15
首先是HTML,然后是脚本。我通过添加一个thrid选项到混合,但使用可以使用手机,工作电话或主电子邮件作为联系方法一个需要更困难的事情。

<div class="form-group">
    <label class="control-label" for="primaryEmail">Primary Email <i class="fa fa-asterisk text-warning"></i></label>
    <input type="text" class="form-control contactMethod" id="primaryEmail" name="primaryEmail" value="" placeholder="Enter email" data-fv-field="contactMethod">
</div>
<div class="form-group">
    <label class="control-label phoneMask" for="cPhone">Cell Phone <i class="fa fa-asterisk text-warning"></i></label>
    <input type="text" class="form-control contactMethod" id="cPhone" name="cPhone" value="" placeholder="Enter cell phone" data-fv-field="contactMethod">
</div>
<div class="form-group">
    <label class="control-label phoneMask" for="wPhone">Work Phone <i class="fa fa-asterisk text-warning"></i></label>
    <input type="text" class="form-control contactMethod" id="wPhone" name="wPhone" value="" placeholder="Enter work phone" data-fv-field="contactMethod">
</div>

我试过几个脚本:

这是最接近http://formvalidation.io/examples/requiring-at-least-one-field/上的例子的那个

$('#leadForm').formValidation({
    framework: 'bootstrap',
    icon: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
        fName: {
            validators: {
                notEmpty: {
                    message: 'The first name is required'
                },
                stringLength: {
                    min: 2,
                    max: 30,
                    message: 'The first name must be more than 2 and less than 30 characters long'
                }
            }
        },
        lName: {
            validators: {
                notEmpty: {
                    message: 'The last name is required'
                },
                stringLength: {
                    min: 2,
                    max: 30,
                    message: 'The last name must be more than 2 and less than 30 characters long'
                }
            }
        },
        secondaryEmail: {
            validators: {
                emailAddress: {
                    message: 'The value is not a valid email address'
                }
            }
        },
        contactMethod: {
            selector: '.contactMethod',
            validators: {
                callback:  function(value, validator, $field) {
                        var isEmpty = true,
                            isValid = false,
                            returnIsValid = false,
                            // Get the list of fields
                            $fields = validator.getFieldElements('contactMethod'),
                            fv = $('#leadForm').data('formValidation');
                        for (var i = 0; i < $fields.length; i++) {
                            thisField = $fields[i].id;
                            // trim value of field
                            thisVal = jQuery.trim($('#'+thisField).val());

                            if(thisVal.length == 0){
                               console.log('empty '+thisField);
                                fv.updateStatus(thisField, 'INVALID', 'callback').updateMessage(thisField,validator,'test');
                            } else {
                                if(thisField == 'cPhone' || thisField == 'wPhone'){
                                    console.log('validating '+thisField);
                                } else if(thisField == 'primaryEmail'){
                                    console.log('validating '+thisField);
                                }
                            }



                            if ($fields.eq(i).val() !== '') {
                                isEmpty = false;
                                break;
                            }
                        }


                        if (!isEmpty) {
                            // Update the status of callback validator for all fields
                            validator.updateStatus('contactMethod', validator.STATUS_VALID, 'callback');
                            returnIsValid = false;
                        } else {

                        }
                        return returnIsValid;
                }
            }
        }
    }

}).on('success.form.fv', function(e) {
    e.preventDefault();
    var $form = $(e.target),
        fv    = $form.data('formValidation');
        // console.log($form.serialize());
        // console.log(fv);
    $.ajax({
        type: 'post',
        url: 'api/add.jsp?surveyId='+cfg['lead.surveyID'],
        data: $form.serialize(),
        dataType: 'json',
        async: false,
        success: function(result){
            console.log(result);

            }
        } 
    });     
});

这更像是@Béranger建议的。它实际上非常接近,但由于这么多的是在keyup它不是触发的提交按钮的点击。我试过添加。

$('#leadForm').formValidation({
    framework: 'bootstrap',
    icon: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
        primaryEmail: {
            validators: {
                notEmpty: {
                    message: 'You must include at least one contact method'
                },
                emailAddress: {
                    message: 'The value is not a valid email address'
                }
            }
        },
        cPhone: {
            validators: {
                notEmpty: {
                    message: 'You must include at least one contact method'
                },
                phone: {
                    country: 'country',
                    message: 'The value is not valid %s phone number'
                }
            }
        },
        wPhone: {
            validators: {
                notEmpty: {
                    message: 'You must include at least one contact method'
                },
                phone: {
                    country: 'country',
                    message: 'The value is not valid %s phone number'
                }
            }
        }
    }
})
.on('keyup', '[name="primaryEmail"], [name="cPhone"], [name="wPhone"]', function(e) {
    var cPhoneIsEmpty = jQuery.trim($('#leadForm').find('[name="cPhone"]').val()) === '',
        wPhoneIsEmpty = jQuery.trim($('#leadForm').find('[name="wPhone"]').val()) === '',
        primaryEmailIsEmpty = jQuery.trim($('#leadForm').find('[name="primaryEmail"]').val()) === '',
        fv = $('#leadForm').data('formValidation');

    var cPhoneIsValid = fv.isValidField('cPhone') === true ? true : false;
    var wPhoneIsValid = fv.isValidField('wPhone') === true ? true : false;
    var primaryEmailIsValid = fv.isValidField('primaryEmail') === true ? true : false;

    switch ($(this).attr('name')) {
        // User is focusing the primaryEmail field
        case 'primaryEmail':
            fv.enableFieldValidators('cPhone', primaryEmailIsEmpty).revalidateField('cPhone');
            fv.enableFieldValidators('wPhone', primaryEmailIsEmpty).revalidateField('wPhone');

            break;

        // User is focusing the cPhone field
       case 'cPhone':
            fv.enableFieldValidators('primaryEmail', cPhoneIsEmpty).revalidateField('primaryEmail');
            fv.enableFieldValidators('wPhone', cPhoneIsEmpty).revalidateField('wPhone');

            break;

        // User is focusing the cPhone field
       case 'wPhone':
            fv.enableFieldValidators('primaryEmail', wPhoneIsEmpty).revalidateField('primaryEmail');
            fv.enableFieldValidators('cPhone', wPhoneIsEmpty).revalidateField('cPhone');

            break;

        default:
            break;
    }

    // if( (cPhoneIsValid || wPhoneIsValid || primaryEmailIsValid)){
    //  fv.enableFieldValidators('primaryEmail', false, 'notEmpty').revalidateField('primaryEmail');
    //  fv.enableFieldValidators('cPhone', false, 'notEmpty').revalidateField('cPhone');
    //  fv.enableFieldValidators('wPhone', false, 'notEmpty').revalidateField('cPhone');
    // } else {
    //  fv.enableFieldValidators('primaryEmail', true).revalidateField('primaryEmail');
    //  fv.enableFieldValidators('cPhone', true).revalidateField('cPhone');
    //  fv.enableFieldValidators('wPhone', true).revalidateField('cPhone');
    // }

    // fv.enableFieldValidators('primaryEmail', true);
    // fv.enableFieldValidators('cPhone', true);
    // fv.enableFieldValidators('wPhone', true);

}).on('success.form.fv', function(e) {
    e.preventDefault();
    // console.log('submit here');
    var $form = $(e.target),
        fv    = $form.data('formValidation');
        // console.log($form.serialize());
        // console.log(fv);
    $.ajax({
        type: 'post',
        url: 'api/add.jsp?surveyId='+cfg['lead.surveyID'],
        data: $form.serialize(),
        dataType: 'json',
        async: false,
        success: function(result){
            console.log(result);
        } 
    });     
});
阅读getFieldElements的文档它不是一个任意的标签。它是您要选择的元素的名称。它返回一个jQuery []所以我猜在底下它只是做一个属性选择类似$(“input [name * =’elementname’]”);我基于这样的事实,在他们的示例中,两个字段都包含“电子邮件”,这是他们选择的名称。没有解释为什么’cm’有任何返回,但他们可能正在做一些其他的魔法。

我怀疑,如果你将联系人字段的名称更改为类似“phoneContact”和“emailContact”

<div class="form-group">
   <label class="control-label" for="emailContact">Primary Email</label>
   <input type="text" class="form-control contactMethod" id="primaryEmail" 
      name="emailContact" value="" placeholder="Enter email">
</div>
<div class="form-group">
   <label class="control-label" for="phoneContact">Cell Phone</label>
   <input type="text" class="form-control contactMethod" id="cPhone" name="phoneContact" 
      value="" placeholder="Enter cell phone">
</div>

然后将您的字段名称更改为“联系人”,您应该会看到这两个字段。

 //...
 $fields = validator.getFieldElements('contact');
 //.. 
 validator.updateStatus('contact', validator.STATUS_VALID, 'callback');
http://stackoverflow.com/questions/30020794/bootstrap-formvalidation-io-trying-to-require-one-field-or-the-other

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:jquery – Bootstrap formvalidation.io试图要求一个字段或其他