JSモード:策略モード、感じは1つの閉鎖して情報を保存するので、それからいくつかの検証方法をプラスします.


<!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>