JS模式:策略模式,感觉就是一个闭包存储信息,然后是加一些验证方法--还看了老半天
运行下面代码
<!DOCTYPE html> <html> <head> <title></title> </head> <body> <script> var varlidator; varlidator = { validate: function(value, type){ var value = value; var type = type; switch(type){ case 'isnonEmpty' : { //..yuju return true; } case 'isNumber' : { //..yuju return true; } case 'isAlphaNum' : { //..yuju return true; } default :{ return 'someting' } } } }; alert(validator.validate('123','isNonEmpty')) ; //有点像命令行模式; var validator = { types : {}, messages : [], config : {}, validate : function(data){ var i, msg , type, checker, result_ok; this.messages = []; for(var i in data){ if(data.hasOwnProperty(i)){ type = this.config[i]; checker = this.types[type]; if(!type){ continue; }; if(!checker){ throw{ name : 'ValidationError', message : 'no handler to validate type '+ type } }; result_ok = checker.validate(data[i]); if( !result_ok ){ msg = 'wrong' + checker.instructions; this.message.push( msg ); } } }; return this.hasErrors(); }, hasErrors : function(){ return this.message.length !== 0 } }; validator.types.inNonEmpty = { validate : function(value){ return value !== ''; }, instructions : 'value can“t be null' }; validator.types.isNumber = { validate : function(value){ return !isNaN( value ) }, instructions : '必须是数字哦' }; validator.types.isAlphaNum = { validator : function(value){ return !/[^a-z0-9]/i,test(value); }, instructions : '必须是数字哦' }; var data = { first_name : 'xx', last_name : '00', age : 26, username : 'qihao' }; validator.config = { first_name : 'isNumber', age : 'isNonEmpty', username : 'isAplhaNum' }; validator.validate( data ); validator.hasErrors(); </script> </body> </html>
天道酬勤
本文作者:方方和圆圆
本文链接:https://www.cnblogs.com/diligenceday/p/3433761.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
分类:
js设计模式的代码
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步