我最近购买并使用了 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;
}
}
}
}
}
});
在示例中,$fields = validator.getFieldElements('cm');
行已用电子邮件替换,但它似乎不是任意标签。但它可能不仅仅是一个与validator.updateStatus('cm', validator.STATUS_VALID, 'callback');
线相匹配的标签。CM 已更改为联系人
所有其他验证似乎都在页面上工作。
更新:
如果我在$fields = validator.getFieldElements('cm');
后立即将$fields
转储到控制台,我会得到"input=([name="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的建议。 它实际上非常接近,但由于其中大部分都在键上,因此单击提交按钮不会触发。 我试过添加。
$('#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">— Or —</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']" );
的属性选择,我基于这样一个事实,即在他们的示例中,两个字段都包含"电子邮件",这是他们选择的名称。当然,这并不能解释为什么"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中的"电子邮件"不是任意的,但实际上是字段"组"的名称(就在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>
您缺少属性数据 fv 字段
正如@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
验证器将空字段标记为有效。