js封装长度验证

function jsChecking(strTxt, minLength, maxLength, strRegular) {
    if (strTxt == null) {
        strTxt = "";
    }
    if (!(strTxt.length >= minLength && strTxt.length <= maxLength)) {
        return "字段长度不再允许范围内,允许输入长度为(" + minLength + "-" + maxLength + ")";
    }
    else if (strRegular != null && strRegular != "") {
        //正则匹配
        var strRl = Regulars[strRegular];
        var reg = new RegExp((strRl==null || strRl=="")?strRegular:strRl);
        if (reg.test(strTxt)) {
            return "";
        }
        else {
            if(strRl==null || strRl=="") return "您输入的信息:“{0}”,不符合要求!".format(strTxt);
            else return returnStr[strRegular].format(strTxt, minLength, maxLength);
        }
    }
}
//正则表达式
var Regulars = {
    Telephone: "^([0-9]{11})?$",
    Phone: "",
    Email: "",
    QQ: "",
    IDCode: "",
    IsIntstr: "",
    IsFloatstr: "",
    IPstr: "",
    AllowNum: "",
    AllowLetter: ""
}
//如果正则表达式没有通过,返回的错误信息
var returnStr = {
    Telephone: "您输入的电话号码:{0}  不符合常规格式!",
    Phone: "",
    Email: "",
    QQ: "",
    IDCode: "",
    IsIntstr: "",
    IsFloatstr: "",
    IPstr: "",
    AllowNum: "",
    AllowLetter: ""
}
//Regulars["UserName"]
String.prototype.format = function (args) {
    var result = this;
    if (arguments.length > 0) {
        if (arguments.length == 1 && typeof (args) == "object") {
            for (var key in args) {
                if (args[key] != undefined) {
                    var reg = new RegExp("({" + key + "})", "g");
                    result = result.replace(reg, args[key]);
                }
            }
        }
        else {
            for (var i = 0; i < arguments.length; i++) {
                if (arguments[i] != undefined) {
                    var reg = new RegExp("({[" + i + "]})", "g");
                    result = result.replace(reg, arguments[i]);
                }
            }
        }
    }
    return result;
}

你可能感兴趣的:(js)