最近项目用到了bootstrap框架,其中前端用的校验,采用的是bootstrapvalidator插件,也是非常强大的一款插件。我这里用的是0.5.2版本。
下面记录一下使用中学习到的相关API,不定期更新。
1. 获取validator对象或实例
一般使用校验是直接调用$(form).bootstrapValidator(options)来初始化validator。初始化后有两种方式获取validator对象或实例,可以用来调用其对象的方法,比如调用resetForm来重置表单。有两种方式获取:
1)
// Get plugin instancevar bootstrapValidator = $(form).data('bootstrapValidator');// and then call methodbootstrapValidator.methodName(parameters)
这种方式获取的是BootstrapValidator的实例,可以直接调用其方法。
2)
$(form).bootstrapValidator(methodName, parameters);
这种方式获取的是代表当前form的jquery对象,调用方式是将方法名和参数分别传入到bootstrapValidator方法中,可以链式调用。
两种方式的使用分别如下:
// 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' } } } } });
新闻热点
疑难解答
图片精选