bootstrapvalidator之API学习教程

最近项目用到了bootstrap框架,其中前端用的校验,采用的是bootstrapvalidator插件,也是非常强大的一款插件。我这里用的是0.5.2版本。

下面记录一下使用中学习到的相关API,不定期更新。

1. 获取validator对象或实例

一般使用校验是直接调用$(form).bootstrapValidator(options)来初始化validator。初始化后有两种方式获取validator对象或实例,可以用来调用其对象的方法,比如调用resetForm来重置表单。有两种方式获取

1)

rush:js;"> // Get plugin instance var bootstrapValidator = $(form).data('bootstrapValidator'); // and then call method bootstrapValidator.methodName(parameters)

这种方式获取的是BootstrapValidator的实例,可以直接调用方法

2)

rush:js;"> $(form).bootstrapValidator(methodName,parameters);

这种方式获取的是代表当前form的jquery对象,调用方式是将方法名和参数分别传入到bootstrapValidator方法中,可以链式调用。 两种方式的使用分别如下:

rush:js;"> // 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属性调用

使用:

rush:js;"> $('#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"]。 使用:

登录失败时,重新启用提交按钮。

<div class="jb51code">
<pre class="brush:js;">
$('#loginForm').bootstrapValidator({
message: 'This value is not valid',FeedbackIcons: {
valid: 'glyphicon glyphicon-ok',invalid: 'glyphicon glyphicon-remove',validating: 'glyphicon glyphicon-refresh'
},submitHandler: function(validator,submitButton) {
$.post(form.attr('action'),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('<a href="https://www.jb51.cc/tag/dis/" target="_blank" class="keywords">dis</a>ableSubmitButtons',false);
    }
  },'json');
},fields: {
  username: {
    validators: {
      notEmpty: {
        message: 'The username is <a href="https://www.jb51.cc/tag/required/" target="_blank" class="keywords">required</a>'
      }
    }
  },password: {
    validators: {
      notEmpty: {
        message: 'The password is <a href="https://www.jb51.cc/tag/required/" target="_blank" class="keywords">required</a>'
      }
    }
  }
}

});

4. enableFieldValidators(field,enabled)

启用或禁用指定字段的所有校验。这里我的实

验结果是如果禁用了校验,好像对应的字段输入(文本框、下拉等)也会变为禁用。 使用:

当密码框不为空时,开启密码框和确认密码框的校验:

rush:js;"> // 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方法可用在需要点击按钮或者链接而非提交对表单进行校验的时候。使用:点击某按钮时,提示所有字段是否通过校验。

rush:js;"> $("#isAllValid").on("click",function(){ alert($("#defaultForm").data('bootstrapValidator').isValid()); });

7. resetForm(Boolean)

重置表单中设置过校验的内容,将隐藏所有错误提示和图标。 使用:

rush:js;"> $("#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,validatorName)

更新指定的字段状态。BootstrapValidator认在校验某个字段合法后不再重新校验,当调用其他插件或者方法可能会改变字段值时,需要重新对该字段进行校验。 使用:

点击按钮对文本框进行赋值,并对其重新校验:

rush:js;"> $('#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方法可用在需要点击按钮或者链接而非提交对表单进行校验的时候。 由第一条可知,调用方式同样有两种:

rush:js;"> $(form).bootstrapValidator(options).bootstrapValidator('validate');

// or
$(form).bootstrapValidator(options);
$(form).data('bootstrapValidator').validate();

11. validateField(field)

对指定的字段进行校验。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程之家。

相关文章

Bootstrip HTML 查询搜索常用格式模版 &lt;form class=&...
如何在按钮上加红色数字 您可以使用Bootstrap的badge组件来在...
要让两个按钮左右排列,你可以使用 Bootstrap 的网格系统将它...
是的,可以将status设置为布尔类型,这样可以在前端使用复选...
前端工程师一般用的是Bootstrap的框架而不是样式,样式一般自...
起步导入:<linkrel="stylesheet"href="b...