/** * 策略类 * @param {number}t 动画已消耗的时间 * @param {number}b 小球的原始位置 * @param {number}c 小球的目标位置 * @param {number}d 动画持续的总时间 */ let tween = { linear: (t, b, c, d) => { return c * t / d + b }, easeIn: (t, b, c, d) => { return c * ( t /= d ) * t + b }, strongEaseIn: (t, b, c, d) => { return c * ( t /= d ) * t * t * t * t + b }, strongEaseOut: (t, b, c, d) => { return c * ( ( t = t / d - 1) * t * t * t * t + 1 ) + b }, sineaseIn: (t, b, c, d) => { return c * ( t /= d) * t * t + b }, sineaseOut: (t, b, c, d) => { return c * ( ( t = t / d - 1) * t * t + 1 ) + b } }
Validator.prototype.start = function () { for (var i = 0, validatorFunc; validatorFunc = this.cache[ i++ ];) { var msg = validatorFunc() if (msg) { return msg } } } // 使用环境 var validateFunc = function () { var validator = new Validator() validator.add(registerForm.userName, 'isNonEmpty', '用户名不能为空') validator.add(registerForm.password, 'minLength:6', '密码长度不能少于6') validator.add(registerForm.phoneNumber, 'isMobile', '手机号码格式不正确') var errorMsg = validator.start() return errorMsg }
var registerForm = document.getElementById('registerForm') registerForm.onsubmit = function () { var errorMsg = validateFunc() if (errorMsg) { alert(errorMsg) returnfalse } }
// 修改Validator类 var Validator = function () { this.cache = [] }
Validator.prototype.add = function (dom, rules) { var self = this for (var i = 0, rule; rule = rules[ i++ ];) { (function (rule) { // rule 为 策略名称:策略参数 的格式 var strategyAry = rule.strategy.split(':') var errorMsg = rule.errorMsg self.cache.push(function () { var strategy = strategyAry.shift() strategyAry.unshift(dom.value) strategyAry.push(errorMsg) // strategyAry = [dom.value, strategyParams, errorMsg] return strategies[strategy].apply(dom, strategyAry) }) })(rule) } }
Validator.prototype.start = function () { for (var i = 0, validatorFunc; validatorFunc = this.cache[ i++ ];) { var msg = validatorFunc() if (msg) { return msg } } } // 使用环境 var validateFunc = function () { var validator = new Validator() validator.add(registerForm.userName, [{ strategy: 'isNonEmpty', errorMsg: '用户名不能为空' }, { strategy: 'minLength:10', errorMsg: '用户名长度不能小于10位' }]) var errorMsg = validator.start() return errorMsg }
var registerForm = document.getElementById('registerForm') registerForm.onsubmit = function () { var errorMsg = validateFunc() if (errorMsg) { alert(errorMsg) returnfalse } }