We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
定义一系列的算法,把它们一个个封装起来,并且使它们可以相互替换。
在表单验证中我们通常需要使用不同的规则校验不同的表单字段。
var strategies = { isNonEmpty: function (value, errorMsg) { // 不为空 if (value === '') { return errorMsg } }, minLength: function (value, length, errorMsg) { // 限制最小长度 if (value.length < length) { return errorMsg } }, isMobile: function (value, errorMsg) { // 手机号码格式 if (!/(^1[3|5|8][0-9]{9}$)/.test(value)) { return errorMsg } } } var validataFunc = function () { var validator = new Validator() // 创建一个 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 = validataFunc() // 如果 errorMsg 有确切的返回值,说明未通过校验 if (errorMsg) { alert(errorMsg) return false // 阻止表单提交 } } var Validator = function () { this.cache = [] // 保存校验规则 } Validator.prototype.add = function (dom, rule, errorMsg) { var ary = rule.split(':') // 把 strategy 和参数分开 this.cache.push(function () { // 把校验的步骤用空函数包装起来,并且放入 cache var strategy = ary.shift() // 用户挑选的 strategy ary.unshift(dom.value) // 把 input 的 value 添加进参数列表 ary.push(errorMsg) // 把 errorMsg 添加进参数列表 return strategies[strategy].apply(dom, ary) }) } Validator.prototype.start = function () { for (var i = 0, validatorFunc; validatorFunc = this.cache[i++];) { var msg = validatorFunc() // 开始校验,并取得校验后的返回信息 if (msg) { // 如果有确切的返回值,说明校验没有通过 return msg } } }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
概念
定义一系列的算法,把它们一个个封装起来,并且使它们可以相互替换。
实现
在表单验证中我们通常需要使用不同的规则校验不同的表单字段。
参考资料
The text was updated successfully, but these errors were encountered: