30

我最近购买并正在使用来自http://formvalidation.io/的 Bootstrap FormValidation 并使用http://formvalidation.io/examples/requiring-at-least-one-field/上的示例我正在尝试设置我的对于需要电子邮件或电话号码,但我无法让示例正常工作。无论我做什么,我都会在主电子邮件字段下看到一条错误消息,上面写着“您必须输入至少一种联系方式”。

如果完整的代码有帮助,我可以发布,但这里是相关的代码片段。

<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到控制台,我会认为它会是一个同时包含 primaryEmail 和 cPhone 的对象。$fields = validator.getFieldElements('cm');"input=([name="primaryEmail"])"

更新 5-18-15 首先是 HTML,然后是脚本。通过在组合中添加第三个选项,我让事情变得更加困难,但使用可以使用手机、工作电话或主要电子邮件作为联系方式,其中一个是必需的。

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

6 回答 6

3

您可以禁用第二个验证并仅在第一个验证错误时启用它:

看看这个链接

<form id="profileForm" method="post">
    <p>Please provide one of these information:</p>

    <div class="form-group">
        <label class="control-label">Social Security Number</label>
        <input type="text" class="form-control" name="ssn" />
    </div>

    <div class="form-group text-center">&mdash; Or &mdash;</div>

    <div class="form-group">
        <label class="control-label">Driver's License Number</label>
        <input type="text" class="form-control" name="driverLicense" />
    </div>

    <div class="form-group">
        <button type="submit" class="btn btn-default">Submit</button>
    </div>
</form>

<script>
$(document).ready(function() {
    $('#profileForm')
        .formValidation({
            framework: 'bootstrap',
            icon: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields: {
                ssn: {
                    validators: {
                        notEmpty: {
                            message: 'Please provide the Social Security number'
                        },
                        regexp: {
                            regexp: /^(?!(000|666|9))\d{3}(?!00)\d{2}(?!0000)\d{4}$/,
                            message: 'The format of your SSN is invalid. It should be XXXXXXXXX with no dashes'
                        }
                    }
                },
                driverLicense: {
                    // Disable validators
                    enabled: false,
                    validators: {
                        notEmpty: {
                            message: 'Or the Drivers License number'
                        },
                        stringLength: {
                            min: 8,
                            max: 20,
                            message: 'The Drivers License number must be more than 8 and less than 20 characters long'
                        }
                    }
                }
            }
        })
        .on('keyup', '[name="ssn"], [name="driverLicense"]', function(e) {
            var driverLicense = $('#profileForm').find('[name="driverLicense"]').val(),
                ssn           = $('#profileForm').find('[name="ssn"]').val(),
                fv            = $('#profileForm').data('formValidation');

            switch ($(this).attr('name')) {
                // User is focusing the ssn field
                case 'ssn':
                    fv.enableFieldValidators('driverLicense', ssn === '').revalidateField('driverLicense');

                    if (ssn && fv.getOptions('ssn', null, 'enabled') === false) {
                        fv.enableFieldValidators('ssn', true).revalidateField('ssn');
                    } else if (ssn === '' && driverLicense !== '') {
                        fv.enableFieldValidators('ssn', false).revalidateField('ssn');
                    }
                    break;

                // User is focusing the drivers license field
                case 'driverLicense':
                    if (driverLicense === '') {
                        fv.enableFieldValidators('ssn', true).revalidateField('ssn');
                    } else if (ssn === '') {
                        fv.enableFieldValidators('ssn', false).revalidateField('ssn');
                    }

                    if (driverLicense && ssn === '' && fv.getOptions('driverLicense', null, 'enabled') === false) {
                        fv.enableFieldValidators('driverLicense', true).revalidateField('driverLicense');
                    }
                    break;

                default:
                    break;
            }
        });
});
</script>
于 2015-05-13T14:31:38.347 回答
1

阅读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');
于 2015-05-06T16:29:17.957 回答
1

由于您使用不同的字段类型,因此您无法像示例中那样对所有输入字段使用相同的验证器对验证进行分组。使用回调为每个字段创建自定义验证器,然后在检测到输入时将所有字段更新为有效,这对我有用。请参阅代码的 javascript 部分...

<script>
$(document).ready(function() {
    $('#profileForm').formValidation({
        framework: 'bootstrap',
        icon: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            primaryEmail: {
                 validators: {
                    callback: {
                        message: 'You must enter atleast one field ',
                        callback: function(value, validator, $field) {
                       if ($("input[name=primaryEmail]").val()) {
                                // Update the status of callback validator for all fields
                                validator.updateStatus('primaryEmail', validator.STATUS_VALID, 'callback');
                                validator.updateStatus('cPhone', validator.STATUS_VALID, 'callback');
                                return true;
                            }
                             return false;
                        }
                    },
                    emailAddress: {
                        message: 'The value is not a valid email address'
                    }
                }
            },//primaryEmail
            cPhone : {
                validators : {
                    callback: {
                        message: 'You must enter atleast one field',
                        callback: function(value, validator, $field) {

                            if ($("input[name=cPhone]").val()) {
                                // Update the status of callback validator for all fields
                                validator.updateStatus('primaryEmail', validator.STATUS_VALID, 'callback');
                                validator.updateStatus('cPhone', validator.STATUS_VALID, 'callback');
                                return true;
                            }
                            return false;
                        }
                    },
                    stringLength: {
                        min: 8,
                        message: "Please enter a contact number with 8 digits"
                    }
                }
            }//cPhone
        }//fields
    });
        $('#profileForm').formValidation().on("success.form.bv", function (e) {
            e.preventDefault();
                    alert('success');
                    $('.form-group').addClass("hidden");
        });
});
</script>
于 2015-05-12T11:15:30.777 回答
0

我不确定,但我认为 getFieldElements 中的“电子邮件”不是任意的,而实际上是字段“组”的名称(就在 之后 fields: {)。你的字段组名称是什么?是cm吗?

可以发全<script>吗?

于 2015-05-06T16:37:27.000 回答
0

检查代码后,我发现您缺少Attribute

这是有效的 HTML

<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" data-fv-field="contact" />
</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" data-fv-field="contact" />
</div>

您缺少 Attribute data-fv-field

于 2015-05-12T16:23:49.573 回答
0

正如@Sen k他在回答中所说:

由于您使用不同的字段类型,因此您无法对所有输入字段使用相同的验证器对验证进行分组......

一个简单的解决方案,您可以使用success.field.fv以下代码中描述的事件:

$('#YourFormId').formValidation({
    framework: 'bootstrap',
    icon: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
        primaryEmail: {
            validators: {
                notEmpty: {},
                emailAddress: {
                    message: 'The value is not a valid email address'
                }
            }
        },
        cPhone: {
            validators: {
                notEmpty: {},
                phone: {
                    country: 'country',
                    message: 'The value is not valid %s phone number'
                }
            }
        }
    }
})
.on('success.field.fv', function(e, data) {
    var primaryEmail = $('[name="primaryEmail"]'),
        cPhone       = $('[name="cPhone"]'),
        validator    = data.fv;

    if (data.field === "primaryEmail" && cPhone.val() === '') {
        // mark the cPhone field as valid if it's empty & the
        // primaryEmail field was valid.
        validator.updateStatus('cPhone', validator.STATUS_VALID, null);
    }

    if (data.field === "cPhone" && primaryEmail.val() === '') {
        // mark the primaryEmail field as valid if it's empty & the
        // cPhone field was valid.
        validator.updateStatus('primaryEmail', validator.STATUS_VALID, null);
    }
});

笔记:

我使用了验证器,notEmpty因为验证器将空字段标记为有效。emailAdressphone

于 2015-05-30T19:23:43.653 回答