您好,登錄后才能下訂單哦!
在建造者模式中動態創建表單時,用戶的輸入是任意的,顯然這是不允許的,我們需要過濾掉用戶不合理的輸入并加以提示,過濾器模式允許開發人員通過不同的標準過濾一組對象,并通過邏輯運算將他們連接起來。
實例中根據表單的要求,設計輸入為空過濾器,郵箱格式過濾器,長度過濾器,并根據用戶的輸入給出結果,其類圖結構如下:
代碼實現:
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>
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。