设计模式 - 策略模式验证提交的表单的使用

news/2024/7/10 22:56:57 标签: 策略模式, javascript, 前端, es6, 设计模式

校验表单的多种规则

javascript">// checkInfo.js 校验表单的文件
// 策略对象
const strategies = {
    // 输入的内容不能为空
    isNoEmpty(value, errorMsg) {
        if (value === '') return errorMsg;
    },
    // 校验姓名的格式
    isCorrectName(value, errorMsg) {
        const regName = /^(?!.*?[\u3000-\u303F\u4DC0-\u4DFF\u2800-\u28FF\u3200-\u32FF\u3300-\u33FF\u2700-\u27BF\u2600-\u26FF\uFE10-\uFE1F\uFE30-\uFE4F])[\u4e00-\u9fbb\u2E80-\uFE4F.·]+$/;
        if (!regName.test(value)) return errorMsg;
    },
    // 校验手机号码
    isCorrectPhone(value, errorMsg) {
        const regPhone = /^1[3456789]\d{9}$/;
        if (!regPhone.test(value)) return errorMsg;
    },
    // 校验身份证
    isCorrectIdCard(value, errorMsg) {
        const isCorrectIdCard = checkIdCard(value);
        if (!isCorrectIdCard) return errorMsg;
    },
    // 限制小长度
    minLength(value, length, errorMsg) {
        if (value.length < length) return errorMsg;
    },
};

// 校验身份证
function checkIdCard(code) {
    if (code.length === 18) {
        code = code.split('');
        // ∑(ai×Wi)(mod 11)
        // 加权因子
        const factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
        // 校验位
        const parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];
        let sum = 0;
        let ai = 0;
        let wi = 0;
        for (let i = 0; i < 17; i++) {
            ai = code[i];
            wi = factor[i];
            sum += ai * wi;
        }
        return parity[sum % 11] == code[17];
    } return code.length === 15;
}
// Validator(验证器)的类
function Validator() {
    this.cache = []; // 效验规则数组
    // 添加校验规则的方法
    // value 接收变单输入的值
    // rules 接受规则的数组
    this.add = function (value, rules) {
        const that = this;
        rules.forEach((item) => {
            const { strategy, errorMsg } = item; // 规则列表的战略与错误提示
            let ary = strategy.split(':'); // 将获取到的strategy(战略,例:minLength:6)分开
            that.cache.push(() => {
            	// 移除并拿到该数组的第一项,用于使用策略对象的方法
                const strategyFun = ary.shift(); 
                ary.unshift(value); // 将value添加到数组的第一项
                ary.push(errorMsg); // 添加到数组的最后一项
                return strategies[strategyFun](...ary); // 将数组作为对应的参数传递给策略对象的方法中
            });
        });
    };
    // 调用检验规则 - 获得校验的方法
    this.start = function () {
        for (let i = 0, validatorFunc; validatorFunc = this.cache[i++];) {
            const msg = validatorFunc();
            if (msg) return msg;
        }
    };
};

标题客户端的使用,导入该文件进入验证方法的使用

javascript">// 姓名的校验规则数组
const nameRule = [{
	strategy: 'isNoEmpty',
	errorMsg: '请输入真实姓名!',
}, {
	strategy: 'isCorrectName',
	errorMsg: '姓名格式填写有误!',
}];
// 身份证
const idCardRule = [{
	strategy: 'isNoEmpty',
	errorMsg: '请输入身份证号码!',
}, {
	strategy: 'isCorrectIdCard',
	errorMsg: '身份证格式填写有误!',
}];
// 手机号码
const phoneRule = [{
	strategy: 'isNoEmpty',
	errorMsg: '请输入手机号码!',
}, {
	strategy: 'isCorrectPhone',
	errorMsg: '手机号码的填写有误!',
}];
// 验证码
const codeRule = [{
	strategy: 'isNoEmpty',
	errorMsg: '请输入验证码!',
}, {
	strategy: 'minLength:6',
	errorMsg: '验证码的填写有误!',
}];
// 定义校验基本信息
function checkInfo(name, idCard, phone, code) {
    const validator = new Validator(); // 创建一个validator对象
    validator.add(name, nameRule); // 添加校验规则
    validator.add(idCard, idCardRule);
    validator.add(phone, phoneRule);
	validator.add(code, codeRule);
	return validator.start(); // 返回校验的errorMsg结果
};
// 提交表单
this.$('#submit_btn').click(() => {
	const name = $('#input_name').val(); // 获取到表单输入框的值
	const idCard= $('#input_idCard').val();
	const phone = $('#input_phone').val();
	const code= $('#input_code').val();
	const errorMsg = checkInfo(name, idCard, phone, code);
	if (errorMsg) {
		// showToast(errorMsg, true); // 验证错误的提示窗
	 	return false;
	}
	// 提交的接口访问....
});

参考书籍《JavaScript设计模式与开发实践》


http://www.niftyadmin.cn/n/1551528.html

相关文章

验证结果与接口返回的提示框引用

面对表单的提示信息&#xff0c;或者接口验证的提示信息错误的弹窗 使用dom的元素写入的方式进行展示 // pageTool.js文件 // 初始化弹窗 const dialog <!-- toast提示 --><div id"toast" class"toast" style"display: none;"><…

scss的常用方法

Sass的介绍 sass的官方网址&#xff1a;https://www.sass.hk/docs/ Sass 是一款强化 CSS 的辅助工具&#xff0c;它在 CSS 语法的基础上增加了变量 (variables)、嵌套 (nested rules)、混合 (mixins)、导入 (inline imports) 等高级功能&#xff0c;这些拓展令 CSS 更加强大与优…

TX Text Control 31.SP3 for Windows Forms Crack

Windows 窗体应用程序的文档处理 将文档编辑、创建和 PDF 生成添加到 Windows 窗体应用程序中。 视窗用户界面 功能齐全的文档编辑器 TX 文本控件是一种完全可编程的丰富编辑控件&#xff0c;可在专为 Visual Studio 设计的可重用组件中为开发人员提供广泛的文字处理功能。它…

手机端设备的的兼容的问题总结

项目在手机端适配的归结 使用rem的来实现适配&#xff0c;在页面中进行对根元素html的font-size设置进行不同设备间的适配 // 屏幕适配 (function (win, doc) {if (!win.addEventListener) return;// 获取对应的浏览器信息var agent navigator.userAgent,isAndroid /(?:And…

whistle的代理接口使用

whistle的使用 whistle是基于Node实现的跨平台抓包调试代理工具&#xff0c;在前端开发中&#xff0c;当后台的接口还未正常使用时&#xff0c;可使用mock将数据代理到本地&#xff0c;这样就可以解决接口还未完善而导致项目无法进行的问题&#xff01; whistle的官方网址&am…

web使用的图片处理

在项目的开发&#xff0c;一般设计的同学都会一个文件夹&#xff0c;里面有对应的切图&#xff0c;psd&#xff08;Photoshop&#xff09;或者sketch&#xff08;ios的sketch应用&#xff09;文件&#xff0c;当切图不能满足我们的需求时&#xff0c;我们可通过源文件进行自我裁…

animation实现简单的loading的动画

转圈的效果&#xff1a; 方法实现一&#xff1a; .loading_circle1 {width: 48px;height: 48px;border-width: 0 0 1px 1px;border-style: solid;border-color: green;border-radius: 50%;animation: loading 1s linear infinite;overflow: hidden; } keyframes loading {0% …

z-index中的层叠规则使用

有关z-index的层叠规则的应用 有关z-index的应用&#xff0c;我们常常会误以为是z-index的值越大层级就越高&#xff0c;在书写项目的弹窗或遮罩层时&#xff0c;把z-index设置成9/99这样的形式&#xff0c;这样可以使页面的层级升高&#xff0c;展示在最上层&#xff01; 但也…