基于Bootstrap的强大jQuery表单验证插件

news/2025/2/7 19:16:41/文章来源:https://www.cnblogs.com/liylllove/p/18583820

预览  下载

formvalidation是一款功能非常强大的基于Bootstrap的JQUERY表单验证插件。该jQuery表单验证插件内置了16种表单验证器,你也可以通过Bootstrap Validator's APIs写自己的表单验证器。该表单验证插件的可用验证器有:

  • between:检测输入的值是否在两个指定的值之间。
  • callback:通过回调函数返回验证信息。
  • creditCard:验证信用卡格式。
  • different:如果输入值和给定的值不同返回true
  • digits:如果输入的值只包含数字返回true
  • emailAddress:验证电子邮件格式是否有效。
  • greaterThan:如果输入的值大于或等于指定的值返回true
  • hexColor:验证一个hex格式的颜色值是否有效。
  • identical:验证输入的值是否和指定字段的值相同。
  • lessThan:如果输入的值小于或等于指定的值返回true
  • notEmpty:检测字段是否为空。
  • regexp:检测输入值是否和指定的javascript正则表达式匹配。
  • remote:通过AJAX请求来执行远程代码。
  • stringLength:验证字符串的长度。
  • uri:验证URL地址是否有效。
  • usZipCode:验证美国的邮政编码格式。

 

 使用方法

使用这个表单验证插件首先要引入必要的js和css文件。jQuery要求1.9.1+以上的版本。

<script src="jquery/1.10.2/jquery.min.js"></script>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css">
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.2/js/bootstrap.min.js"></script>
<script type="text/javascript" src="../dist/js/bootstrapValidator.js"></script>
<link rel="stylesheet" href="../dist/css/bootstrapValidator.css"/>              
 HTML结构

该表单验证插件的最基本例子的HTML结果如下:

<form id="defaultForm" method="post" class="form-horizontal">
  <div class="form-group">
    <label class="col-lg-3 control-label">Username</label>
    <div class="col-lg-5">
      <input type="text" class="form-control" name="username" />
    </div>
  </div>
  <div class="form-group">
    <label class="col-lg-3 control-label">Email address</label>
    <div class="col-lg-5">
      <input type="text" class="form-control" name="email" />
    </div>
  </div>
  <div class="form-group">
    <label class="col-lg-3 control-label">Password</label>
    <div class="col-lg-5">
      <input type="password" class="form-control" name="password" />
    </div>
  </div>
  <div class="form-group">
    <label class="col-lg-3 control-label">Retype password</label>
    <div class="col-lg-5">
      <input type="password" class="form-control" name="confirmPassword" />
    </div>
  </div>
  <div class="form-group">
    <label class="col-lg-3 control-label" id="captchaOperation"></label>
    <div class="col-lg-2">
      <input type="text" class="form-control" name="captcha" />
    </div>
  </div>
  <div class="form-group">
    <div class="col-lg-9 col-lg-offset-3">
      <button type="submit" class="btn btn-primary">Sign up</button>
    </div>
  </div>
</form>               
 JAVASCRIPT

在页面加载完毕之后,通过下面的方法来初始化该表单验证插件:

<script type="text/javascript">
  $(document).ready(function() {
  // Generate a simple captcha
  function randomNumber(min, max) {
  return Math.floor(Math.random() * (max - min + 1) + min);
  };
  $('#captchaOperation').html([randomNumber(1, 100), '+', randomNumber(1, 200), '='].join(' '));
 
  $('#defaultForm').bootstrapValidator({
    message: 'This value is not valid',
      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'
      },
      regexp: {
        regexp: /^[a-zA-Z0-9_\.]+$/,
        message: 'The username can only consist of alphabetical, number, dot and underscore'
        },
        different: {
        field: 'password',
        message: 'The username and password can\'t be the same as each other'
        }
      }
    },
    email: {
      validators: {
        notEmpty: {
          message: 'The email address is required and can\'t be empty'
        },
        emailAddress: {
          message: 'The input is not a valid email address'
        }
      }
    },
    password: {
    validators: {
      notEmpty: {
          message: 'The password is required and can\'t be empty'
        },
        identical: {
          field: 'confirmPassword',
          message: 'The password and its confirm are not the same'
        },
        different: {
          field: 'username',
          message: 'The password can\'t be the same as username'
        }
      }
    },
    confirmPassword: {
      validators: {
        notEmpty: {
        message: 'The confirm password is required and can\'t be empty'
        },
        identical: {
        field: 'password',
        message: 'The password and its confirm are not the same'
        },
        different: {
        field: 'username',
        message: 'The password can\'t be the same as username'
        }
      }
    },
    captcha: {
      validators: {
        callback: {
          message: 'Wrong answer',
          callback: function(value, validator) {
          var items = $('#captchaOperation').html().split(' '), sum = parseInt(items[0]) + parseInt(items[2]);
          return value == sum;
          }
        }
      }
    }
  }
  });
});
</script>

 配置参数

该表单验证插件的默认参数配置如下:

// The first invalid field will be focused automatically
autoFocus: true,
 
// Support declarative usage (setting options via HTML 5 attributes)
// Setting to false can improve the performance
declarative: true,
 
// The form CSS class
elementClass: 'fv-form',
 
// Use custom event name to avoid window.onerror being invoked by jQuery
// See #630
events: {
  // Support backward
  formInit: 'init.form.fv',
  formError: 'err.form.fv',
  formSuccess: 'success.form.fv',
  fieldAdded: 'added.field.fv',
  fieldRemoved: 'removed.field.fv',
  fieldInit: 'init.field.fv',
  fieldError: 'err.field.fv',
  fieldSuccess: 'success.field.fv',
  fieldStatus: 'status.field.fv',
  localeChanged: 'changed.locale.fv',
  validatorError: 'err.validator.fv',
  validatorSuccess: 'success.validator.fv'
},
 
// Indicate fields which won't be validated
// By default, the plugin will not validate the following kind of fields:
// - disabled
// - hidden
// - invisible
//
// The setting consists of jQuery filters. Accept 3 formats:
// - A string. Use a comma to separate filter
// - An array. Each element is a filter
// - An array. Each element can be a callback function
//    function($field, validator) {
//  $field is jQuery object representing the field element
//  validator is the BootstrapValidator instance
//  return true or false;
//    }
//
// The 3 following settings are equivalent:
//
// 1) ':disabled, :hidden, :not(:visible)'
// 2) [':disabled', ':hidden', ':not(:visible)']
// 3) [':disabled', ':hidden', function($field) {
//return !$field.is(':visible');
//  }]
excluded: [':disabled', ':hidden', ':not(:visible)'],
 
// Map the field name with validator rules
fields: null,
 
// Live validating option
// Can be one of 3 values:
// - enabled: The plugin validates fields as soon as they are changed
// - disabled: Disable the live validating. The error messages are only shown after the form is submitted
// - submitted: The live validating is enabled after the form is submitted
live: 'enabled',
 
// Locale in the format of languagecode_COUNTRYCODE
locale: 'en_US',
 
// Default invalid message
message: 'This value is not valid',
 
// The field will not be live validated if its length is less than this number of characters
threshold: null,
 
// Whether to be verbose when validating a field or not.
// Possible values:
// - true:  when a field has multiple validators, all of them will be checked, and respectively - if errors occur in
//  multiple validators, all of them will be displayed to the user
// - false: when a field has multiple validators, validation for this field will be terminated upon the first encountered error.
//  Thus, only the very first error message related to this field will be displayed to the user
verbose: true,
 
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// These options mostly are overridden by specific framework
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 
button: {
  // The submit buttons selector
  // These buttons will be disabled to prevent the valid form from multiple submissions
  selector: '[type="submit"]',
 
  // The disabled class
  disabled: ''
},
 
control: {
  // The CSS class for valid control
  valid: '',
 
  // The CSS class for invalid control
  invalid: ''
},
 
err: {
  // The CSS class of each message element
  clazz: '',
 
  // The error messages container. It can be:
  // - 'tooltip' if you want to use Bootstrap tooltip to show error messages
  // - 'popover' if you want to use Bootstrap popover to show error messages
  // - a CSS selector indicating the container
  // In the first two cases, since the tooltip/popover should be small enough, the plugin only shows only one error message
  // You also can define the message container for particular field
  container: null,
 
  // Used to determine where the messages are placed
  parent: null
},
 
// Shows ok/error/loading icons based on the field validity.
icon: {
  valid: null,
  invalid: null,
  validating: null,
  feedback: ''
},
 
row: {
  // The CSS selector for indicating the element consists of the field
  // You should adjust this option if your form group consists of many fields which not all of them need to be validated
  selector: null,
  valid: '',
  invalid: '',
  feedback: ''
}  

 

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/846034.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

人员跌倒检测算法

人员跌倒检测算法利用基于YOLOv5和CNN,人员跌倒检测算法通过安装在监测区域内的摄像头对人员的行为进行检测,区分正常活动和跌倒等异常行为。一旦检测到跌倒行为,系统会立即触发报警,通过声音警报、短信通知、APP推送等多种方式发出报警通知,确保相关人员能够在第一时间知…

秒开超大文件夹:如何禁止 Windows 自动识别文件夹类型

Windows 的「自动文件类型发现」功能会分析文件夹内容,以便应用最合适的视图模板。但对于包含大量文件和文件类型复杂的超大文件夹,则会导致「文件资源管理器」的打开速度变慢。本文将教你如何关闭这一功能,以加快文件夹的加载速度。 .wwads-img img { width: 150px; margin…

垃圾分类AI视觉识别系统

垃圾分类AI视觉识别系统通过高清摄像头实时捕捉垃圾投放点,垃圾分类AI视觉识别系统通过YOLOv7算法进行图像识别,识别出垃圾乱投、垃圾箱满溢、厨余垃圾误时投放等违规行为。这种智能分析算法不仅提高了识别的准确性,还能够实时监控垃圾投放点的状态,确保垃圾分类的规范性。…

学生上课行为教学评估检测系统

学生上课行为教学评估检测系统的核心在于智能识别技术,学生上课行为教学评估检测系统能够通过人脸识别与表情识别技术,捕捉学生在课堂上的面部表情和情绪变化,从而分析学生的参与度和兴趣点。人脸考勤功能则确保了出勤率的准确性,为教学管理提供了基础数据。声纹识别技术的…

电动车戴头盔智能识别系统方案

电动车戴头盔智能识别系统方案核心在于YOLOv7算法与RNN的结合,电动车戴头盔智能识别系统方案通过部署在交通要道的实时监控摄像头捕捉画面,自动识别出画面中的电动车骑行者,判断是否佩戴了安全头盔。一旦系统检测到未佩戴安全头盔的骑行者,将立即触发报警机制。报警信号不仅…

工厂车间智能视频监控系统

工厂车间智能视频监控系统对工厂车间人员行为与着装的实时监测,工厂车间智能视频监控系统通过对摄像机画面内人员的穿戴及行为进行实时监测,包括睡岗、离岗、玩手机、抽烟、摔倒等行为,以及是否穿戴反光服、安全帽、口罩、护目镜、安全带、工服等防护设备。这种监测不仅提高…

检查棋盘方格颜色---字符串

题目 String类型解答 class Solution { public boolean checkTwoChessboards(String s, String t) { int a = (s.charAt(0) + s.charAt(1)) % 2; int b = (t.charAt(0) + t.charAt(1)) % 2; return a == b; } }

让任务动起来!看板方法彻底改变你的工作方式

在现代高效工作中,“规划意识”是每个人必备的软技能。无论是个人项目还是团队协作,合理规划不仅是完成任务的保障,更是培养全局视野的重要手段。但很多人困惑于如何培养规划意识,这里分享一个简单却深刻的方法——通过在线协作看板工具将目标“具体化”和“可视化”。 目标…

C# 如何在 PropertyGrid 中,对同一double的成员显示出不同的长度的内容?

这段时间搞东西,接触到这个,整了好几天。终于 Stackoverflow 上找到一个与我思路上一样的答案。之前用了好多遍 百度 AI 的方法都牛头不对马嘴。 看来 自己对 这一套 C# 的中的反射机制中的内容还不是太熟悉。所以摸了好久。 主要思路是这样的: PropertyGrid 可以把一个对象…

【每日一题】20241203

我觉得人活着吧,有些事儿就得逼着自己不去想。因为想了,你就感觉没法活;想活,你就不能想。【每日一题】如图所示,将物块 \(a\) 分别放入光滑的 \(A\) 轨道和 \(B\) 轨道的最高点,以零初速度滑至轨道的最低点所用时间分别为 \(t_1\) 与 \(t_2\).则已知 \(A\) 轨道与 \(B\…

编译OpenCV——ubuntu x86_64平台

在x86_64平台上编译得到两个版本的opencv:x86_64和arm64 方式与此博客一样编译OpenCV——jetson嵌入式平台 - 夕西行 - 博客园,区别只有如下几个地方 1、编译x86_64版本时最终放到默认的/usr/local目录里 2、编译arm64版本时 最终放到/opt/opencv_aarch64目录里,以便与本地默…

Azure DevOps搭建自动化部署CICD流水线

微软的CICD 1.完成CICD的组件叫做 Azure Devops 官方的链接:https://dev.azure.com/ Azure Devops 我们用的是微软的 - 云平台 不需要部署到本地部署到云上就可以了 第二种方式CICD 大多数企业不是微软系的 常用这个 Azure Devops jinkes 本期用的是第一种,微软的 (1)第一…