尝试要求一个字段或另一个字段

时间:2015-05-04 00:00:23

标签: jquery twitter-bootstrap formvalidation-plugin

我最近购买并使用了来自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之后立即将$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);
        } 
    });     
});

6 个答案:

答案 0 :(得分:3)

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

看看this link

extern

答案 1 :(得分:1)

阅读getFieldElements的文档,它不是任意标签。它是您要选择的元素的名称。它返回一个jQuery [],所以我猜测它只是做一个类似于$( "input[name*='elementname']" );的属性选择我基于这样的事实:在他们的例子中,这两个字段都包含&#39; email&#39;这就是他们选择的名字。当然,这并没有解释为什么&#39; cm&#39;有任何回报,但他们可能正在做一些其他的魔术。

我怀疑如果您将联系人字段的名称更改为&#39; phoneContact&#39;和&#39; emailContact&#39;

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

然后将您的字段名称更改为“联系”&#39;你应该看到两个领域。

 //...
 $fields = validator.getFieldElements('contact');
 //.. 
 validator.updateStatus('contact', validator.STATUS_VALID, 'callback');

答案 2 :(得分: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>

答案 3 :(得分:0)

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

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

答案 4 :(得分:0)

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

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

答案 5 :(得分:0)

正如subrepo在他的回答中所说:

  

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

一个简单的解决方案,您可以使用事件@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); } }); 验证程序,因为notEmptyemailAdress验证程序将空字段标记为有效。