对于bootstrap的表单校验,网上有很多插件,在使用了bootstrapvalidator 插件后,把遇到的问题记录下来。首先是对每一个字段写校验:$('#form').bootstrapValidator({
message: 'This value is not valid',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
firstName: {
validators: {
notEmpty: {
message: 'The first name is required and cannot be empty'
}
}
},
lastName: {
validators: {
notEmpty: {
message: 'The last name is required and cannot be empty'
}
}
},
username: {
message: 'The username is not valid',
validators: {
notEmpty: {
message: 'The username is required and cannot be empty'
},
stringLength: {
min: 6,
max: 30,
message: 'The username must be more than 6 and less than 30 characters long'
},
regexp: {
regexp: /^[a-zA-Z0-9_\.]+$/,
message: 'The username can only consist of alphabetical, number, dot and underscore'
},
remote: {
url: 'remote.php',
message: 'The username is not available'
},
different: {
field: 'password',
message: 'The username and password cannot be the same as each other'
}
}
},
email: {
validators: {
emailAddress: {
message: 'The input is not a valid email address'
}
}
},
password: {
validators: {
notEmpty: {
message: 'The password is required and cannot be empty'
},
identical: {
field: 'confirmPassword',
message: 'The password and its confirm are not the same'
},
different: {
field: 'username',
message: 'The password cannot be the same as username'
}
}
}
}
});
然后开启校验://方式1:
$('#form').bootstrapValidator('validate');
//方式2:
$("#form").data("bootstrapValidator").validate();
判断校验是否通过:$("#form").data("bootstrapValidator").isValid();
重置表单:$('#form').data('bootstrapValidator').resetForm();
但是遇到一个问题要是实现一个radio组怎么办,当radio的值为0,校验生效,radio为1时校验不生效怎么办。网上找了很多方法:动态为字段添加校验$('#form').bootstrapValidator('addField', 'field', {
validators: {
notEmpty: {
message: '内容不能为空'
}
}
});
怎样对字段移除校验呢?//方式1:结果报错
$('#form').bootstrapValidator('removeField', "field");
//方式2:结果报错
$('#form').data('bootstrapValidator')
.updateStatus('field', 'NOT_VALIDATED', null)
.validateField('filed');
或
$('#form')
.bootstrapValidator('updateStatus', $('#text'), 'NOT_VALIDATED')
.bootstrapValidator('validateField', $('#text'));
});
//方式3:这个方法可行
$('#form').data('bootstrapValidator').enableFieldValidators("field",false);//校验失效
$('#form').data('bootstrapValidator').enableFieldValidators("field",false);//校验生效