标签:过滤器模式、表单验证
在建造者模式中动态创建表单时,用户的输入是任意的,显然这是不允许的,我们需要过滤掉用户不合理的输入并加以提示,过滤器模式允许开发人员通过不同的标准过滤一组对象,并通过逻辑运算将他们连接起来。
实例中根据表单的要求,设计输入为空过滤器,邮箱格式过滤器,长度过滤器,并根据用户的输入给出结果,其类图结构如下:
代码实现:
var Filter = Class.extend({ controls:[], ctor:function(_controls = []){ this.controls = _controls; }, addControl:function(_control){ this.controls.push(_control); }, filter:function(){ return []; } }); var EmailFilter = Filter.extend({ filter:function(){ var myreg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/; for(var i in this.controls){ var txt = document.getElementById(this.controls[i].id).value; if(!myreg.test(txt)) { console.log(this.controls[i].label + "不符合邮件格式"); } } } }); var LengthFilter = Filter.extend({ filter:function(){ for(var i in this.controls){ var txt = document.getElementById(this.controls[i].id).value; if(txt.length < 6){ console.log(this.controls[i].label + "长度不能小于6"); } } } }); var EmptyFilter = Filter.extend({ filter:function(){ for(var i in this.controls){ var txt = document.getElementById(this.controls[i].id).value; if(txt == ""){ console.log(this.controls[i].label + "不能为空"); } } } }); <body> <form id = "form1" action = "#" method = "post"> </form> </body> <script> var empty_filter,email_filter,length_filter; (function(){ var name = new Input("邮箱","username","username","text"); var password = new Input("密码","password","password","password"); var submit = new Button("提交","sub","sub",submitForm); var form = new Form("form1",[]); form.addControl(name).addControl(password).addControl(submit).build(); empty_filter = new EmptyFilter(); length_filter = new LengthFilter(); email_filter = new EmailFilter(); empty_filter.addControl(name); empty_filter.addControl(password); email_filter.addControl(name); length_filter.addControl(password); })(); function submitForm(){ empty_filter.filter(); email_filter.filter(); length_filter.filter(); } </script>
本文出自 “走一停二回头看三” 博客,请务必保留此出处http://janwool.blog.51cto.com/5694960/1882313
标签:过滤器模式、表单验证
原文地址:http://janwool.blog.51cto.com/5694960/1882313