js 策略模式 实现表单验证
策略模式
简单点说就是:实现目标的方式有很多种,你可以根据自己身情况选一个方法来实现目标.
所以至少有2个对象 . 一个是策略类,一个是环境类(上下文). 然后自己就可以根据上下文选择不同的策略来执行方案.
策略模式的优点:
1. 策略模式利用组合、委托和多态等技术和思想,可以有效地避免多重条件选择语句
2. 策略模式提供了对开放-封闭原则的完美支持,将算法封装在独立的 策略类 中,使得它们易于切换,易于理解,易于扩展.
// html
- <!DOCTYPE html>
- <head>
- <meta charset="utf8">
- <title>策略模式实现表单验证</title>
- <link rel="stylesheet" type="text/css" href="style.css">
- <script src="rule.js"></script>
- <script src="validator.js"></script>
- </head>
- <body>
- <form action="#" method="GET" id="form">
- <div class="field">
- <label>用户名</label>
- <input type="text" name="name">
- </div>
- <div class="field">
- <label>联系电话</label>
- <input type="text" name="mobile">
- </div>
- <div class="field">
- <label>邮箱</label>
- <input type="text" name="email">
- </div>
- <button class="submit" type="submit">提交</button>
- </form>
- <script>
- let dom = document.getElementById("form");
- let formValid = new FormValid(dom);
- formValid.add({
- field: "name",
- rule: new RequiredRule(),
- errormsg: "字段必填"
- })
- formValid.add({
- field: "name",
- rule: new LengthRule(10),
- errormsg: "限定长度为10个字符"
- })
- formValid.add({
- field: "mobile",
- rule: new MobileRule(),
- errormsg: "手机号码错误"
- })
- formValid.add({
- field: "email",
- rule: new EmailRule(),
- errormsg: "邮箱格式错误"
- })
- dom.onsubmit = function (event) {
- let result = formValid.isValid();
- if (result !== true) {
- alert(result);
- return false;
- }
- alert("提交成功");
- }
- </script>
- </body>
- </html>
// css
- #form{
- margin: 50px auto;
- width: 500px;
- }
- input {
- width: 350px;
- height: 24px;
- padding: 0 4px;
- float: left;
- }
- .field{
- margin-top: 10px;
- overflow: hidden;
- }
- label {
- float: left;
- text-align: right;
- width: 100px;
- overflow: hidden;
- padding-right: 5px;
- }
- .submit{
- margin-top: 20px;
- margin-left:104px;
- }
// 策略类
- /**
- * 必填
- */
- class RequiredRule {
- /**
- * 验证
- * @param {string} value 值
- * @param {string} errormsg 错误信息
- * @param {any} attach 附加参数
- * @returns {string|bool}
- */
- test(value, errormsg, attach) {
- return /^(:?\s*)$/.test(value) ? errormsg : true;
- }
- }
- /**
- * 范围
- */
- class RangeRule {
- /**
- * 构造函数
- * @param {array} range
- */
- constructor(range) {
- this.range = range;
- }
- /**
- * 验证
- * @param {string} value 值
- * @param {string} errormsg 错误信息
- * @returns {string|bool}
- */
- test(value, errormsg) {
- value = Number.parseFloat(value);
- if (this.range[0] <= value && this.range[1] > value) {
- return true;
- }
- return errormsg;
- }
- }
- /**
- * 有效数值验证
- */
- class NumberRule {
- /**
- * 验证
- * @param {string} value 值
- * @param {string} errormsg 错误信息
- * @returns {string|bool}
- */
- test(value, errormsg) {
- return /^(?:\d+)$/.test(value) || errormsg;
- }
- }
- /**
- * 邮箱验证
- * 格式:登录名@主机名.域名
- */
- class EmailRule {
- constructor() {
- this.rule = new RegExp(/(?:\w+)@(?:\w+)\.(?:\w+)/);
- }
- /**
- * 验证
- * @param {string} value 值
- * @param {string} errormsg 错误信息
- * @returns {string|bool}
- */
- test(value, errormsg) {
- return this.rule.test(value) || errormsg;
- }
- }
- /**
- * 手机号验证
- */
- class MobileRule {
- constructor() {
- this.rule = new RegExp(/^1\d{10}$/);
- }
- /**
- * 验证
- * @param {string} value 值
- * @param {string} errormsg 错误信息
- * @returns {string|bool}
- */
- test(value, errormsg) {
- return this.rule.test(value) || errormsg;
- }
- }
- class LengthRule {
- constructor(maxlength) {
- this.maxlength = maxlength;
- }
- /**
- * 验证
- * @param {string} value 值
- * @param {string} errormsg 错误信息
- * @returns {string|bool}
- */
- test(value, errormsg) {
- return value.length > this.maxlength ? errormsg : true;
- }
- }
// 环境类
- class FormValid {
- /**
- * 构造函数
- * @param {HTMLFormElement} form 元素节点
- */
- constructor(form) {
- this.form = form;
- this.rules = [];
- }
- /**
- * 添加验证规则
- * @param {object} option
- * @param {string} option.field 字段名
- * @param {object} option.rule 规则
- * @param {string} option.errormsg 错误信息
- */
- add({ field, rule, errormsg }) {
- if (typeof rule.test == "function" && this.form[field]) {
- this.rules.push(() => {
- return rule.test(this.form[field].value, errormsg);
- });
- }
- }
- isValid() {
- let result = [];
- for (let i = 0; i < this.rules.length; i++) {
- let r = this.rules[i]();
- if (r !== true) result.push(r);
- }
- return result.length > 0 ? result : true;
- }
- }
源码: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 策略模式 实现表单验证的更多相关文章
- 使用JavaScript策略模式校验表单
表单校验 Web项目中,登录,注册等等功能都需要表单提交,当把用户的数据提交给后台之前,前端一般要做一些力所能及的校验,比如是否填写,填写的长度,密码是否符合规范等等,前端校验可以避免提交不合规范的表 ...
- jquery.validate.js使用之自定义表单验证规则
jquery.validate.js使用之自定义表单验证规则,下面列出了一些常用的验证法规则 jquery.validate.js演示查看 jquery validate强大的jquery表单验证插件 ...
- JS组件系列——Form表单验证神器: BootstrapValidator
前言:做Web开发的我们,表单验证是再常见不过的需求了.友好的错误提示能增加用户体验.博主搜索bootstrap表单验证,搜到的结果大部分都是文中的主题:bootstrapvalidator.今天就来 ...
- 关于JS中的常用表单验证+正则表达式
一.非空验证 trim:去空格(去掉前后的空格),任何字符串都可以用这个方法.写法为:if(v.trim().length==0),表示如果去掉空格后的字符串的长度为0. <body> & ...
- JavaScript设计模式 - 策略模式(表单验证)
表单提交的时候,总是要校验,不同的表单可能校验相同的功能. 为了避免代码重复的复制黏贴,使用策略模式,写出来的代码赏心悦目,且可扩展,还可以作为插件到处使用 <!DOCTYPE html> ...
- 微信小程序之表单验证
表单验证 何为表单验证呢? 百度百科给出的回答是这样的: 表单验证是javascript中的高级选项之一.JavaScript 可用来在数据被送往服务器前对 HTML 表单中的这些输入数据进行验证 [ ...
- jQuery表单验证组件BootstrapValidator
github:https://github.com/nghuuphuoc/bootstrapvalidator 参考博客:JS组件系列——Form表单验证神器: BootstrapValidator ...
- summernote富文本编辑器配合validate表单验证无法进行表单提交的问题
1.使用summernote富文本编辑器提交图片到服务器 在使用bootstrap中,我们用到了summernote富文本编辑器,使用summernote将图片上传到服务器中,参考我的上篇文章http ...
- jquery.validation.js 表单验证
jquery.validation.js 表单验证 官网地址:http://bassistance.de/jquery-plugins/jquery-plugin-validation jQuer ...
随机推荐
- node.js服务器搭建
//1.导入http 核心模块 const http = require("http"); //2.调用http.createServer 方法,创建一个web 服务器对象 con ...
- Java核心技术卷一基础知识-第14章-多线程-读书笔记
第 14 章 多线程 本章内容: * 什么是线程 * 中断线程 * 线程状态 * 线程属性 * 同步 * 阻塞队列 * 线程安全的集合 * Collable与Future * 执行器 * 同步器 * ...
- Tomcat 启动时项目报错 org.springframework.beans.factory.BeanCreationException
事情是这样的,最近我们公司需要将开发环境和测试环境分开,所以就需要把所有的项目部署一套新的开发环境. 我们都是通过 Jenkins 进行部署的,先说一下两个环境的配置: 测试环境配置(旧):jdk1. ...
- phtoshop cs6 下载安装及破解方法(另附Photoshop CC 2018破解版图文教程)
前言: 前端虽然用PS不多,但有时需要用PS切图:UI给你PSD图,需要取色,查看字体颜色大小:测量元素宽高等 但有时想找一个“麻雀虽小,五脏俱全”又是破解版的PS,也不是那么容易的 注:ps完整版不 ...
- C++版 - LeetCode 145: Binary Tree Postorder Traversal(二叉树的后序遍历,迭代法)
145. Binary Tree Postorder Traversal Total Submissions: 271797 Difficulty: Hard 提交网址: https://leetco ...
- 开发属于自己的Web服务器
本文基于.net core 的控制台程序作为服务端 main函数: class Program { static void Main(string[] args) { Console.WriteLin ...
- [疑难杂症]__当你的Cortana搜索无法使用,显示纯白界面(ps:已解决).
前言 这个问题是在前不久解决关于我电脑点击屏幕上方快捷方式不久后出现的问题,之前并没有出现过这样的错误,但因为使用到的情况比较少,就一直没有去解决,但在一点时间后,发现没有Cortana搜索栏还是十分 ...
- MySQL索引的概念
索引是一种特殊的文件(InnoDB数据表上的索引是表空间的一个组成部分),它们包含着对数据表里所有记录的引用指针.更通俗的说,数据库索引好比是一本书前面的目录,能加快数据库的查询速度. 索引分为聚簇索 ...
- 【转载】浅谈38K红外发射接受编码
转自Doctor_A 坛友的笔记! 之前做接触过一次红外遥控器,现在有空想用简单的话来聊一聊,下面有错误的地方欢迎改正指出: 1:红外的概念不聊,那是一种物理存在.以下聊38K红外发射接收,主要讲可编 ...
- 【原创】uC/OS II 任务切换原理
今天学习了uC/OS II的任务切换,知道要实现任务的切换,要将原先任务的寄存器压入任务堆栈,再将新任务中任务堆栈的寄存器内容弹出到CPU的寄存器,其中的CS.IP寄存器没有出栈和入栈指令,所以只能引 ...