最近项目用到了bootstrap框架,其中前端用的校验,采用的是bootstrapvalidator插件,也是非常强大的一款插件。我这里用的是0.5.2版本。
下面记录一下使用中学习到的相关API,不定期更新。
1. 获取validator对象或实例
一般使用校验是直接调用$(form).bootstrapValidator(options)来初始化validator。初始化后有两种方式获取validator对象或实例,可以用来调用其对象的方法,比如调用resetForm来重置表单。有两种方式获取:
1)
// Get plugin instance var bootstrapValidator = $(form).data(\'bootstrapValidator\'); // and then call method bootstrapValidator.methodName(parameters)
这种方式获取的是BootstrapValidator的实例,可以直接调用其方法。
2)
两种方式的使用分别如下:
// The first way $(form) .data(\'bootstrapValidator\') .updateStatus(\'birthday\', \'NOT_VALIDATED\') .validateField(\'birthday\'); // The second one $(form) .bootstrapValidator(\'updateStatus\', \'birthday\', \'NOT_VALIDATED\') .bootstrapValidator(\'validateField\', \'birthday\');
2. defaultSubmit()
使用默认的提交方式提交表单,调用此方法BootstrapValidator将不执行任何的校验。一般需要时可以放在validator校验的submitHandler属性里调用。
使用:
$(\'#defaultForm\').bootstrapValidator({ fields: { username: { message: \'The username is not valid\', validators: { notEmpty: { message: \'The username is required and can\\'t be empty\' } } } }, submitHandler: function(validator, form, submitButton) { // a) // Use Ajax to submit form data //$.post(form.attr(\'action\'), form.serialize(), function(result) { // ... process the result ... //}, \'json\'); //b) // Do your task // ... // Submit the form validator.defaultSubmit(); } });
3. disableSubmitButtons(boolean)
启用或禁用提交按钮。BootstrapValidator里默认的提交按钮是所有表单内的type属性值为submit的按钮,即[type="submit"]。
使用:
当登录失败时,重新启用提交按钮。
$(\'#loginForm\').bootstrapValidator({ message: \'This value is not valid\', feedbackIcons: { valid: \'glyphicon glyphicon-ok\', invalid: \'glyphicon glyphicon-remove\', validating: \'glyphicon glyphicon-refresh\' }, submitHandler: function(validator, form, submitButton) { $.post(form.attr(\'action\'), form.serialize(), function(result) { // The result is a JSON formatted by your back-end // I assume the format is as following: // { // valid: true, // false if the account is not found // username: \'Username\', // null if the account is not found // } if (result.valid == true || result.valid == \'true\') { // You can reload the current location window.location.reload(); // Or use Javascript to update your page, such as showing the account name // $(\'#welcome\').html(\'Hello \' + result.username); } else { // The account is not found // Show the errors $(\'#errors\').html(\'The account is not found\').removeClass(\'hide\'); // Enable the submit buttons $(\'#loginForm\').bootstrapValidator(\'disableSubmitButtons\', false); } }, \'json\'); }, fields: { username: { validators: { notEmpty: { message: \'The username is required\' } } }, password: { validators: { notEmpty: { message: \'The password is required\' } } } } });
4. enableFieldValidators(field, enabled)
启用或禁用指定字段的所有校验。这里我的实验结果是如果禁用了校验,好像对应的字段输入(文本框、下拉等)也会变为禁用。
使用:
当密码框不为空时,开启密码框和确认密码框的校验:
// Enable the password/confirm password validators if the password is not empty $(\'#signupForm\').find(\'[name="password"]\').on(\'keyup\', function() { var isEmpty = $(this).val() == \'\'; $(\'#signupForm\').bootstrapValidator(\'enableFieldValidators\', \'password\', !isEmpty) .bootstrapValidator(\'enableFieldValidators\', \'confirm_password\', !isEmpty); if ($(this).val().length == 1) { $(\'#signupForm\').bootstrapValidator(\'validateField\', \'password\') .bootstrapValidator(\'validateField\', \'confirm_password\'); } });
5. getFieldElements(field)根据指定的name获取指定的元素,返回值是null或一个jquery对象数组。
6. isValid()返回当前需要验证的所有字段是否都合法。调用此方法前需先调用validate来进行验证,validate方法可用在需要点击按钮或者链接而非提交对表单进行校验的时候。使用:点击某按钮时,提示所有字段是否通过校验。
$("#isAllValid").on("click", function(){
alert($("#defaultForm").data(\'bootstrapValidator\').isValid());
});
7. resetForm(Boolean)
重置表单中设置过校验的内容,将隐藏所有错误提示和图标。
使用:
$("#isAllValid").on("click", function(){
alert($("#defaultForm").data(\'bootstrapValidator\').isValid());
if(!$("#defaultForm").data(\'bootstrapValidator\').isValid()) {
$("#defaultForm").data(\'bootstrapValidator\').resetForm();
}
});
8. updateElementStatus($field, status, validatorName)
更新元素状态。status的值有:NOT_VALIDATED, VALIDATING, INVALID or VALID。
9. updateStatus(field, status, validatorName)
更新指定的字段状态。BootstrapValidator默认在校验某个字段合法后不再重新校验,当调用其他插件或者方法可能会改变字段值时,需要重新对该字段进行校验。
使用:
点击按钮对文本框进行赋值,并对其重新校验:
$(\'#defaultForm\').bootstrapValidator({ fields: { username: { message: \'The username is not valid\', validators: { notEmpty: { message: \'The username is required and can\\'t be empty\' } } }, stringLength: { min: 6, max: 30, message: \'The username must be more than 6 and less than 30 characters long\' } } }); $("#setname").on("click", function(){ $("input[name=username]").val(\'san\'); var bootstrapValidator = $("#defaultForm").data(\'bootstrapValidator\'); bootstrapValidator.updateStatus(\'username\', \'NOT_VALIDATED\').validateField(\'username\'); //错误提示信息变了 });
10. validate()
手动对表单进行校验,validate方法可用在需要点击按钮或者链接而非提交对表单进行校验的时候。
由第一条可知,调用方式同样有两种:
$(form).bootstrapValidator(options).bootstrapValidator(\'validate\'); // or $(form).bootstrapValidator(options); $(form).data(\'bootstrapValidator\').validate();
11. validateField(field)
对指定的字段进行校验。