繁体   English   中英

尝试要求一个字段或另一个字段的bootstrap formvalidation.io

[英]Bootstrap formvalidation.io trying to require one field or the other

我最近购买并正在使用从引导FormValidation http://formvalidation.io/和使用上的例子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;
                            }
                        }
                    }
                }
            }
        });

在exmaple行$fields = validator.getFieldElements('cm'); cm替换为电子邮件,但它确实看起来只是一个任意标签。 但它可能不仅仅是与validator.updateStatus('cm', validator.STATUS_VALID, 'callback');匹配的标签validator.updateStatus('cm', validator.STATUS_VALID, 'callback'); 线。 cm已更改为联系人

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

更新:

如果我在$fields = validator.getFieldElements('cm');之后立即将$fields转储到控制台$fields = validator.getFieldElements('cm'); 我得到"input=([name="primaryEmail"])"我本以为它会是一个同时包含primaryEmail和cPhone的对象。

更新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);
        } 
    });     
});

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

看看这个链接

<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>

阅读getFieldElements的文档,它不是任意标签。 它是您要选择的元素的名称。 它返回一个jQuery []所以我猜测它只是做一个类似于$( "input[name*='elementname']" );的属性选择$( "input[name*='elementname']" ); 我的基础是,在他们的例子中,这两个字段都包含'email',这是他们选择的名称。 虽然没有解释为什么'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');

由于您使用的是不同的字段类型,因此无法像在示例中那样对所有输入字段使用相同的验证器对验证进行分组。 使用回调为每个字段创建自定义验证器,然后在检测到输入时将所有字段更新为有效。 查看代码的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>

我不确定,但我认为getFieldElements中的“email”不是任意的,但实际上是字段“group”的名称(就在fields: { )。 你的现场组名称是什么? cm吗?

你可以发布整个<script>吗?

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

这是有效的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>

您缺少属性data-fv-field

正如@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验证标记空字段为有效。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM