当前位置: 代码迷 >> JavaScript >> 印证JavaScript函数的参数
  详细解决方案

印证JavaScript函数的参数

热度:499   发布时间:2012-11-23 22:54:33.0
验证JavaScript函数的参数

一段简单代码,用于验证JavaScript函数中的参数个数,类型等

?

使用方法:

在每个函数执行前调用验证函数,如果验证未通过,验证函数将返回true,否则返回false或者null

?

?

String.__typeName = "string";
Number.__typeName = "number";
Array.__typeName = "array";
Function.__typeName = "function";
Object.__typeName = "object";

ffap = {};

ffap.Utils = {
    _isInstanceOfType: function(type, instance){
        if (type === String) {
            return (typeof instance === "string");
        }
        if (type === Number) {
            return (typeof instance === "number");
        }
        if (type === Boolean) {
            return (typeof instance === "boolean");
        }
        return instance instanceof type;
    },
    
    /**
     * 验证函数参数
     *
     * @param {Object} params			待验证的参数
     * @param {Object} expectedParams	期望的参数
     * @param {Object} validateParameterCount	是否验证参数个数,默认为true
     */
    validateParams: function(params, expectedParams, validateParameterCount){
        /* 待验证的参数个数 */
        var expectedLength = expectedParams.length, error = false;
        validateParameterCount = validateParameterCount !== false;
        
        error = ffap.Utils._validateParameterCount(params, expectedParams, validateParameterCount);
        if (error) {
            return true;
        }
        
        for (var i = 0, l = params.length; i < l; i++) {
            var expectedParam = expectedParams[Math.min(i, expectedLength - 1)], paramName = expectedParam.name;
            if (expectedParam.parameterArray) {
                paramName += "[" + (i - expectedLength + 1) + "]";
            }
            else 
                if (!validateParameterCount && (i >= expectedLength)) {
                    break;
                }
            error = ffap.Utils._validateParameter(params[i], expectedParam, paramName);
            if (error) {
                return error;
            }
        }
        return false;
    },
    
    
    _validateParameterCount: function(params, expectedParams, validateParameterCount){
        var i, error, expectedLen = expectedParams.length, actualLen = params.length;
        if (actualLen < expectedLen) {
            var minParams = expectedLen;
            for (i = 0; i < expectedLen; i++) {
                var param = expectedParams[i];
                if (param.optional || param.parameterArray) {
                    minParams--;
                }
            }
            if (actualLen < minParams) {
                error = true;
            }
        }
        else 
            if (validateParameterCount && (actualLen > expectedLen)) {
                error = true;
                for (i = 0; i < expectedLen; i++) {
                    if (expectedParams[i].parameterArray) {
                        error = false;
                        break;
                    }
                }
            }
        if (error) {
            console.log("参数个数不正确");
            return true;
        }
        
        return false;
    },
    
    _validateParameter: function(param, expectedParam, paramName){
        var error, expectedType = expectedParam.type, expectedInteger = !!expectedParam.integer, expectedDomElement = !!expectedParam.domElement, mayBeNull = !!expectedParam.mayBeNull;
        
        error = ffap.Utils._validateParameterType(param, expectedType, expectedInteger, expectedDomElement, mayBeNull, paramName);
        if (error) {
            return error;
        }
        
        var expectedElementType = expectedParam.elementType, elementMayBeNull = !!expectedParam.elementMayBeNull;
        
        if (expectedType === Array && typeof(param) !== "undefined" && param !== null &&
        (expectedElementType || !elementMayBeNull)) {
            var expectedElementInteger = !!expectedParam.elementInteger, expectedElementDomElement = !!expectedParam.elementDomElement;
            for (var i = 0; i < param.length; i++) {
                var elem = param[i];
                error = ffap.Utils._validateParameterType(elem, expectedElementType, expectedElementInteger, expectedElementDomElement, elementMayBeNull, paramName + "[" + i + "]");
                if (error) {
                    return error;
                }
            }
        }
        
        return false;
    },
    
    _validateParameterType: function(param, expectedType, expectedInteger, expectedDomElement, mayBeNull, paramName){
        var error, i;
        
        if (typeof(param) === "undefined") {
            if (mayBeNull) {
                return null;
            }
            else {
                console.log("参数" + paramName + "不能为undefined");
                return true;
            }
        }
        
        if (param === null) {
            if (mayBeNull) {
                return null;
            }
            else {
                console.log("参数" + paramName + "不能为null");
                return true;
            }
        }
        
        
        if (expectedType && !ffap.Utils._isInstanceOfType(expectedType, param)) {
            console.log("参数{" + paramName + ":" + param + "}的类型不匹配\n" + "应为:" + expectedType.__typeName + "\n实际为:" + typeof param);
            return true;
        }
        
        if (expectedType === Number && expectedInteger) {
            if ((param % 1) !== 0) {
                console.log("参数{" + paramName + ":" + param + "}不是整数");
                return true;
            }
        }
        
        return false;
    }
};

?

?

使用:

?

function func(a, b, c){
    var error = ffap.Utils.validateParams(arguments, [{
        name: "a",
        type: Array,
        mayBeNull: false,
        optional: true,
        
        elementType: Number,
        elementMayBeNull: false
    }, {
        name: "b",
        type: Boolean,
        mayBeNull: false,
        optional: false
    }, {
        name: "c",
        type: Number,
        mayBeNull: false,
        optional: false
    }]);
    
    if (error) {
        return;
    }
    
    执行原来其他函数体...
}

?

?

参数描述见下表:

?

属性

描述

type

期望的参数类型。可取值包括StringNumber、 ? Boolean、ArrayFunctionObject

mayBeNull

如果为true,参数可以为null

optional

如果为true,参数可以忽略

integer

如果参数是一个Number,指定是否必须为整数

elementType

如果参数是一个Array,指定其元素的期望类型,

可取值与type属性相同

elementMayBeNull

如果参数是一个Array,指定是否可以包含null元素

elementInteger

如果参数是一个Array,指定其元素是否为整数

?

其中错误信息使用的是FireBug的console打印

  相关解决方案