策略模式

简单点说就是:实现目标的方式有很多种,你可以根据自己身情况选一个方法来实现目标.

所以至少有2个对象 .  一个是策略类,一个是环境类(上下文). 然后自己就可以根据上下文选择不同的策略来执行方案.

策略模式的优点:
  1. 策略模式利用组合、委托和多态等技术和思想,可以有效地避免多重条件选择语句
  2. 策略模式提供了对开放-封闭原则的完美支持,将算法封装在独立的 策略类 中,使得它们易于切换,易于理解,易于扩展.

// html

  1. <!DOCTYPE html>
  2.  
  3. <head>
  4. <meta charset="utf8">
  5. <title>策略模式实现表单验证</title>
  6. <link rel="stylesheet" type="text/css" href="style.css">
  7. <script src="rule.js"></script>
  8. <script src="validator.js"></script>
  9. </head>
  10.  
  11. <body>
  12. <form action="#" method="GET" id="form">
  13. <div class="field">
  14. <label>用户名</label>
  15. <input type="text" name="name">
  16. </div>
  17. <div class="field">
  18. <label>联系电话</label>
  19. <input type="text" name="mobile">
  20. </div>
  21. <div class="field">
  22. <label>邮箱</label>
  23. <input type="text" name="email">
  24. </div>
  25. <button class="submit" type="submit">提交</button>
  26. </form>
  27. <script>
  28. let dom = document.getElementById("form");
  29.  
  30. let formValid = new FormValid(dom);
  31.  
  32. formValid.add({
  33. field: "name",
  34. rule: new RequiredRule(),
  35. errormsg: "字段必填"
  36. })
  37.  
  38. formValid.add({
  39. field: "name",
  40. rule: new LengthRule(10),
  41. errormsg: "限定长度为10个字符"
  42. })
  43.  
  44. formValid.add({
  45. field: "mobile",
  46. rule: new MobileRule(),
  47. errormsg: "手机号码错误"
  48. })
  49.  
  50. formValid.add({
  51. field: "email",
  52. rule: new EmailRule(),
  53. errormsg: "邮箱格式错误"
  54. })
  55.  
  56. dom.onsubmit = function (event) {
  57. let result = formValid.isValid();
  58. if (result !== true) {
  59. alert(result);
  60. return false;
  61. }
  62. alert("提交成功");
  63. }
  64.  
  65. </script>
  66. </body>
  67.  
  68. </html>

// css

  1. #form{
  2. margin: 50px auto;
  3. width: 500px;
  4. }
  5.  
  6. input {
  7. width: 350px;
  8. height: 24px;
  9. padding: 0 4px;
  10. float: left;
  11. }
  12.  
  13. .field{
  14. margin-top: 10px;
  15. overflow: hidden;
  16. }
  17. label {
  18. float: left;
  19. text-align: right;
  20. width: 100px;
  21. overflow: hidden;
  22. padding-right: 5px;
  23. }
  24. .submit{
  25. margin-top: 20px;
  26. margin-left:104px;
  27. }

// 策略类

  1. /**
  2. * 必填
  3. */
  4. class RequiredRule {
  5.  
  6. /**
  7. * 验证
  8. * @param {string} value 值
  9. * @param {string} errormsg 错误信息
  10. * @param {any} attach 附加参数
  11. * @returns {string|bool}
  12. */
  13. test(value, errormsg, attach) {
  14. return /^(:?\s*)$/.test(value) ? errormsg : true;
  15. }
  16. }
  17.  
  18. /**
  19. * 范围
  20. */
  21. class RangeRule {
  22.  
  23. /**
  24. * 构造函数
  25. * @param {array} range
  26. */
  27. constructor(range) {
  28. this.range = range;
  29. }
  30.  
  31. /**
  32. * 验证
  33. * @param {string} value 值
  34. * @param {string} errormsg 错误信息
  35. * @returns {string|bool}
  36. */
  37. test(value, errormsg) {
  38. value = Number.parseFloat(value);
  39. if (this.range[0] <= value && this.range[1] > value) {
  40. return true;
  41. }
  42. return errormsg;
  43. }
  44. }
  45.  
  46. /**
  47. * 有效数值验证
  48. */
  49. class NumberRule {
  50. /**
  51. * 验证
  52. * @param {string} value 值
  53. * @param {string} errormsg 错误信息
  54. * @returns {string|bool}
  55. */
  56. test(value, errormsg) {
  57. return /^(?:\d+)$/.test(value) || errormsg;
  58. }
  59. }
  60.  
  61. /**
  62. * 邮箱验证
  63. * 格式:登录名@主机名.域名
  64. */
  65. class EmailRule {
  66.  
  67. constructor() {
  68. this.rule = new RegExp(/(?:\w+)@(?:\w+)\.(?:\w+)/);
  69. }
  70.  
  71. /**
  72. * 验证
  73. * @param {string} value 值
  74. * @param {string} errormsg 错误信息
  75. * @returns {string|bool}
  76. */
  77. test(value, errormsg) {
  78. return this.rule.test(value) || errormsg;
  79. }
  80. }
  81.  
  82. /**
  83. * 手机号验证
  84. */
  85. class MobileRule {
  86. constructor() {
  87. this.rule = new RegExp(/^1\d{10}$/);
  88. }
  89.  
  90. /**
  91. * 验证
  92. * @param {string} value 值
  93. * @param {string} errormsg 错误信息
  94. * @returns {string|bool}
  95. */
  96. test(value, errormsg) {
  97. return this.rule.test(value) || errormsg;
  98. }
  99. }
  100.  
  101. class LengthRule {
  102. constructor(maxlength) {
  103. this.maxlength = maxlength;
  104. }
  105.  
  106. /**
  107. * 验证
  108. * @param {string} value 值
  109. * @param {string} errormsg 错误信息
  110. * @returns {string|bool}
  111. */
  112. test(value, errormsg) {
  113. return value.length > this.maxlength ? errormsg : true;
  114. }
  115. }

// 环境类

  1. class FormValid {
  2.  
  3. /**
  4. * 构造函数
  5. * @param {HTMLFormElement} form 元素节点
  6. */
  7. constructor(form) {
  8. this.form = form;
  9. this.rules = [];
  10. }
  11.  
  12. /**
  13. * 添加验证规则
  14. * @param {object} option
  15. * @param {string} option.field 字段名
  16. * @param {object} option.rule 规则
  17. * @param {string} option.errormsg 错误信息
  18. */
  19. add({ field, rule, errormsg }) {
  20. if (typeof rule.test == "function" && this.form[field]) {
  21. this.rules.push(() => {
  22. return rule.test(this.form[field].value, errormsg);
  23. });
  24. }
  25. }
  26.  
  27. isValid() {
  28. let result = [];
  29. for (let i = 0; i < this.rules.length; i++) {
  30. let r = this.rules[i]();
  31. if (r !== true) result.push(r);
  32. }
  33. return result.length > 0 ? result : true;
  34. }
  35. }

源码:https://pan.baidu.com/s/17_oBg1dqmbxAdG_AW3sWgg

样本:http://js.zhuamimi.cn/%E8%A1%A8%E5%8D%95%E9%AA%8C%E8%AF%81/

js 策略模式 实现表单验证的更多相关文章

  1. 使用JavaScript策略模式校验表单

    表单校验 Web项目中,登录,注册等等功能都需要表单提交,当把用户的数据提交给后台之前,前端一般要做一些力所能及的校验,比如是否填写,填写的长度,密码是否符合规范等等,前端校验可以避免提交不合规范的表 ...

  2. jquery.validate.js使用之自定义表单验证规则

    jquery.validate.js使用之自定义表单验证规则,下面列出了一些常用的验证法规则 jquery.validate.js演示查看 jquery validate强大的jquery表单验证插件 ...

  3. JS组件系列——Form表单验证神器: BootstrapValidator

    前言:做Web开发的我们,表单验证是再常见不过的需求了.友好的错误提示能增加用户体验.博主搜索bootstrap表单验证,搜到的结果大部分都是文中的主题:bootstrapvalidator.今天就来 ...

  4. 关于JS中的常用表单验证+正则表达式

    一.非空验证 trim:去空格(去掉前后的空格),任何字符串都可以用这个方法.写法为:if(v.trim().length==0),表示如果去掉空格后的字符串的长度为0. <body> & ...

  5. JavaScript设计模式 - 策略模式(表单验证)

    表单提交的时候,总是要校验,不同的表单可能校验相同的功能. 为了避免代码重复的复制黏贴,使用策略模式,写出来的代码赏心悦目,且可扩展,还可以作为插件到处使用 <!DOCTYPE html> ...

  6. 微信小程序之表单验证

    表单验证 何为表单验证呢? 百度百科给出的回答是这样的: 表单验证是javascript中的高级选项之一.JavaScript 可用来在数据被送往服务器前对 HTML 表单中的这些输入数据进行验证 [ ...

  7. jQuery表单验证组件BootstrapValidator

    github:https://github.com/nghuuphuoc/bootstrapvalidator 参考博客:JS组件系列——Form表单验证神器: BootstrapValidator ...

  8. summernote富文本编辑器配合validate表单验证无法进行表单提交的问题

    1.使用summernote富文本编辑器提交图片到服务器 在使用bootstrap中,我们用到了summernote富文本编辑器,使用summernote将图片上传到服务器中,参考我的上篇文章http ...

  9. jquery.validation.js 表单验证

    jquery.validation.js 表单验证   官网地址:http://bassistance.de/jquery-plugins/jquery-plugin-validation jQuer ...

随机推荐

  1. node.js服务器搭建

    //1.导入http 核心模块 const http = require("http"); //2.调用http.createServer 方法,创建一个web 服务器对象 con ...

  2. Java核心技术卷一基础知识-第14章-多线程-读书笔记

    第 14 章 多线程 本章内容: * 什么是线程 * 中断线程 * 线程状态 * 线程属性 * 同步 * 阻塞队列 * 线程安全的集合 * Collable与Future * 执行器 * 同步器 * ...

  3. Tomcat 启动时项目报错 org.springframework.beans.factory.BeanCreationException

    事情是这样的,最近我们公司需要将开发环境和测试环境分开,所以就需要把所有的项目部署一套新的开发环境. 我们都是通过 Jenkins 进行部署的,先说一下两个环境的配置: 测试环境配置(旧):jdk1. ...

  4. phtoshop cs6 下载安装及破解方法(另附Photoshop CC 2018破解版图文教程)

    前言: 前端虽然用PS不多,但有时需要用PS切图:UI给你PSD图,需要取色,查看字体颜色大小:测量元素宽高等 但有时想找一个“麻雀虽小,五脏俱全”又是破解版的PS,也不是那么容易的 注:ps完整版不 ...

  5. C++版 - LeetCode 145: Binary Tree Postorder Traversal(二叉树的后序遍历,迭代法)

    145. Binary Tree Postorder Traversal Total Submissions: 271797 Difficulty: Hard 提交网址: https://leetco ...

  6. 开发属于自己的Web服务器

    本文基于.net core 的控制台程序作为服务端 main函数: class Program { static void Main(string[] args) { Console.WriteLin ...

  7. [疑难杂症]__当你的Cortana搜索无法使用,显示纯白界面(ps:已解决).

    前言 这个问题是在前不久解决关于我电脑点击屏幕上方快捷方式不久后出现的问题,之前并没有出现过这样的错误,但因为使用到的情况比较少,就一直没有去解决,但在一点时间后,发现没有Cortana搜索栏还是十分 ...

  8. MySQL索引的概念

    索引是一种特殊的文件(InnoDB数据表上的索引是表空间的一个组成部分),它们包含着对数据表里所有记录的引用指针.更通俗的说,数据库索引好比是一本书前面的目录,能加快数据库的查询速度. 索引分为聚簇索 ...

  9. 【转载】浅谈38K红外发射接受编码

    转自Doctor_A 坛友的笔记! 之前做接触过一次红外遥控器,现在有空想用简单的话来聊一聊,下面有错误的地方欢迎改正指出: 1:红外的概念不聊,那是一种物理存在.以下聊38K红外发射接收,主要讲可编 ...

  10. 【原创】uC/OS II 任务切换原理

    今天学习了uC/OS II的任务切换,知道要实现任务的切换,要将原先任务的寄存器压入任务堆栈,再将新任务中任务堆栈的寄存器内容弹出到CPU的寄存器,其中的CS.IP寄存器没有出栈和入栈指令,所以只能引 ...