javascript设计模式之策略模式

数据验证之简易方式

// 举例 常见的验证表单字段经常是if else 或者 switch case

var validater = {

    validate: function (value, type) {

        switch (type) {

            case 'isNonEmpty ':                

                break; // NonEmpty 验证结果

            case 'isNumber ': 

                break; // Number 验证结果

            case 'isAlphaNum ':

                break; // AlphaNum 验证结果

            default: 

                return true;

        }

    }

};



// 测试

alert(validater.validate("123", "isNonEmpty"));

 

数据验证之策略模式

// source: http://jsfiddle.net/ganksolo/4ezZ4/



/* 

 * 策略模式

 * 策略模式定义了一系列算法,这些算法都是做相同的事情,只是实现不同

 * 减少了算法类与使用算法类之间的耦合

*/



/* 

 * 算法封装 -> 需要验证的数据 -> 根据数据配置验证器规则(策略模式的体现)

 * 1.把验证的算法分别封装起来,让统一的验证器(validator)来分别处理

 * 2.开发者只需提供需要验证的表单数据(可以是一个js对象)算法

 * 3.开发者根据需要验证的数据(这里指表单数据),设置验证器有效规则的可接受规则(为了使验证器知道最好的策略)

*/

var validator = {



    // 所有用于验证规则的处理程序

    arithmetic: {},



    // 错误消息

    messages: [],



    // 当前验证的配置

    config: {},



    // 接口方法 传入的参数是 key => value对

    validate: function (data) {

        var i, msg, type, checker, result_ok;



        // 重置所有消息

        this.messages = [];



        for (i in data) {

            if (data.hasOwnProperty(i)) {



                // 根据key查询是否有存在的验证规则

                type = this.config[i];



                // 获取验证规则的验证处理程序

                checker = this.arithmetic[type];



                // 如果验证规则不存在,则不处理

                if (!type) {

                    continue;  

                }



                // 如果验证处理程序不存在,抛出异常

                if (!checker) {

                    throw {

                        name: "ValidationError",

                        message: "没有处理程序来验证类型 " + type

                    }

                }



                // 验证结果

                result_ok = checker.validate(data[i]);



                if (!result_ok) {

                    msg = "无效值为 " + i + " ," + checker.instructions;

                    this.messages.push(msg);

                }

            }

        }



        return !this.hasErrors();  // 验证通过了吗

    },



    // 帮助程序

    hasErrors: function () {

        return this.messages.length !== 0;

    }

};



// 算法封装

validator.arithmetic = {

    // 空值检测

    isNonEmpty: {

        validate: function (value) {

            return value !== "";

        },

        instructions: "传入的值不能为空!"

    },



    // 检测汉字

    isZhCn: {

        validate: function (value) {

            return /^[\u4e00-\u9fa5]+$/.test(value);

        },

        instructions: "请输入汉字!"

    },



    // 检测手机号码

    isTel: {

        validate: function (value) {

            return /1\d{10}/.test(value);

        },

        instructions: "请输入正确的手机号码!"

    },



    // 检测改值只能包含字母和数字

    isAlphaNum: {

        validate: function (value) {

            return /[a-z0-9]/i.test(value);

        },

        instructions: "传入的值只能包含字母和数字,不能包含特殊字符"

    }

};



// 需要验证的数据

var data = {

    name: "name",

    tel: 1555

};



// 配置验证器规则

validator.config = {

    name: "isZhCn",

    tel: "isTel"

};



// 测试

validator.validate(data);



(function () {

    if (validator.hasErrors()) {



        //console.log(validator.messages.join("\n"));

        if (validator.messages.join("").indexOf("name") !== -1) {

            console.log("请输入汉字");

            return false;

        }



        if (validator.messages.join("").indexOf("tel") !== -1) {

            console.log("请输入手机号码");

            return false;

        }

    }

})();

 

你可能感兴趣的:(JavaScript)