【问题标题】:Bootstrap formvalidation.io trying to require one field or the otherBootstrap formvalidation.io 试图要求一个字段或另一个
【发布时间】:2015-05-04 00:00:23
【问题描述】:

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

如果完整代码有帮助,我可以发布,但这里是相关代码 sn-ps。

<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 替换为 email,但它似乎不是任意标签。但它可能不仅仅是与validator.updateStatus('cm', validator.STATUS_VALID, 'callback'); 行匹配的标签。 cm已改为联系方式

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

更新:

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

2015 年 5 月 18 日更新 首先是 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);
        } 
    });     
});

【问题讨论】:

  • 如果您已付费,请联系他们的支持。
  • @Lance 试试我发布的选项。
  • 我已经发布了额外的脚本。它变得非常令人沮丧。 @MelanciaUK。我曾尝试发布到他们的 Twitter 帐户,但该网站没有实际的“支持”链接或电子邮件。所以这很令人沮丧。
  • @Lance 支持在这个 repo https://github.com/formvalidation/support
  • 我已经尝试在 github 上发布到支持但没有得到回应。所以这个问题仍然存在(并且令人沮丧)

标签: jquery twitter-bootstrap formvalidation-plugin


【解决方案1】:

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

看看this link

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

【讨论】:

  • 到目前为止,这是最接近实际解决问题的方法。我昨晚试过了,让它部分工作。今晚我会尝试更多,如果我能做到,我会标记这个答案并给予赏金。我想我越来越近了
  • 很高兴阅读。如果您有其他错误,请告诉我们
  • 这是一个好的开始,但仍然无法正常工作。大问题是它取决于keyup,如果用户进入表单以编辑现有数据,并且如果他们不与这些字段交互并点击提交,他们(在您的情况下)拥有 ssn 但没有驾照密钥 ip 不会触发,并且会在驾驶执照下向用户显示一条消息,说即使 ssn 已经归档,也需要一个字段
【解决方案2】:

阅读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');

【讨论】:

    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

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

      你能发布整个&lt;script&gt;吗?

      【讨论】:

      • 我认为您和@jared 说的基本相同。我确实尝试将我的cm 修改为contact,并在field: {} 联系人之后调用了该组。尽管这确实对处理事情的方式进行了一些更改,但并没有使其按预期工作。我今晚会发布完整的脚本
      • 嗯,代码看起来不错。愚蠢的问题:您是否尝试颠倒顺序,首先检查“emptyness”,然后检查每个字段(基本上将contact validator移到顶部, 就在field: { ) 之后?
      【解决方案5】:

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

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

      【讨论】:

      • 添加这个属性似乎并不能解决问题。
      【解决方案6】:

      正如@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 验证器,因为emailAdress 和phone 验证器将空字段标记为有效。

      【讨论】:

        猜你喜欢
        • 2017-09-11
        • 2020-11-11
        • 1970-01-01
        • 2014-07-24
        • 2015-01-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多