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>

 

posted @ 2013-11-20 15:53  方方和圆圆  阅读(372)  评论(0编辑  收藏  举报

再过一百年, 我会在哪里?