﻿
$.include('jquery.inputvalidate.js', ['css/jquery.inputvalidate.css']);
/*
@   蒋峰 2009-04-09 新增
@   此脚本用来对页面文本框进行格式验证
@   用法：
通过自定义属性的方法，对文本框的属性进行了预定义，预定义的属性包含：
属性名         属性参数            描述
trim           true/false          去除用户输入的左右空格 true:执行 false:不执行
required       true/false          是否必填项 true:执行，生成必填项标识，如果未输入数据，消息框提示。false:不执行，即非必填项
maxlength      int型数据           用户可输入最大长度  超出最大长度将不会录入
datatype       枚举类型            用户可自定义格式化的数据 目前可接受的格式化数据有：int,float,email 可以无限扩展
dataattach     int型数据           此属性只有在datatype='float'时才起作用，用来标识浮点数的小数点位数.例:datatype='float' dataattach='5'
errormessage   字符串数据          用户自定义的错误提示消息、定义了此属性，预定义的错误提示信息将会失效
------------------------------------------------------------------------------------------------------------
@   此脚本是在Jquery的基础上扩展而成，因此在引用此脚本之前要引用Jquery的JS文件。在页面上设置文本框的属性后，即可完成对文本框的验证。

@   在页面提交时的验证需要在所要进行提交操作的对象上绑定InputValidate()方法，此方法将对整个页面的文本框进行格式验证。
*/



//@需要预定义几个样式表：
//@.input_text_required 必填项
//@.input_text_ok       数据验证成功
//@.input_text_wrong    数据验证错误

//预定义错误提示
var $_ERROR_MESSAGE = {
    REQUIRED: "必填字段.",
    INT: "只能输入整数.",
    FLOAT: "只能输入浮点数.",
    ENGLISH: "只能输入英文",
    CHINESE: "只能输入中文",
    EMAIL: "EMail格式错误.",
    MOBILE: "手机格式错误",
    TELEPHONE: "电话格式错误.格式：010-55555555",
    SQL: "请不要输入系统敏感字符.",
    URL: "网址格式错误."
}
//预定义的正则表达式
var $_REGEXP = {
    INT: /[0-9]/,
    FLOAT: /[0-9.]/,
    ENGLISH: /[a-zA-Z]\w{0,25}/,
    CHINESE: /^[\u0391-\uFFE5]+$/,
    EMAIL: /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/,
    MOBILE: /^((\(\d{2,3}\))|(\d{3}\-))?((13)|(15))\d{9}$/,
    TELEPHONE: /^((\(\d{2,3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,8}(\-\d{1,5})?$/,
    URL: /^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\:+!]*([^<>\\])*$/
}

//黏贴事件
function inputTextOnPaste() {
    event.returnValue = !isNaN(window.clipboardData.getData('Text'));
}

//只能输入阿拉伯数字
function inputTextOnKeyPressWithInt() {
    event.returnValue = /[0-9]/.test(String.fromCharCode(event.keyCode));
}

//只能输入浮点数数据，且能指定小数点位数
function inputTextOnKeyPressWithFloat(decimalDigits) {
    var keycode = String.fromCharCode(event.keyCode);
    var value = event.srcElement.value;
    var flag = /[0-9.]/.test(keycode);
    var pointIndex = value.indexOf('.');
    if (decimalDigits == null || decimalDigits == "") {
        decimalDigits = 2;
    }
    if (flag && keycode == '.') {
        flag = pointIndex == -1;
    }
    else if (flag && pointIndex != -1) {
        flag = value.substring(pointIndex).length <= parseInt(decimalDigits);
    }
    event.returnValue = flag;
}

//@外部控件引用方法
//@用户可通过在控件事件上通过引用此方法来对页面上所有的文本框进行格式验证
//@在页面上存在必填项，且必填项没有添加数据时，将会阻断数据的提交，并显示必填项的错误提示
//@在页面上存在格式化数据，且已经输入了错误的数据时，将会阻断数据的提交，并显示错误信息提示
function InputValidate() {
    var returnValue = true;
    //检验必填项文本框
    $(":text[required='true'],:password[required='true']").each(function() {
        var msg = "";
        if ($(this).attr('errormessage') != null) {
            msg = $(this).attr('errormessage');
        }
        if ($.trim($(this).val()).length == 0) {
            if ($('#' + $(this).attr('id') + '_error').length > 0) {
                $('#' + $(this).attr('id') + '_error').show('slow');
            } else {
                //$('#' + $(this).attr('id') + '_msg').after("<div id='" + $(this).attr('id') + "_error' class='div_notes_required'>" + (msg != "" ? msg : $_ERROR_MESSAGE.REQUIRED) + "</div>");
                $('#' + $(this).attr('id') + '_msg').after("<span id='" + $(this).attr('id') + "_error' class='input_text_required'>" + (msg != "" ? msg : $_ERROR_MESSAGE.REQUIRED) + "</span>");
            }
            returnValue = false;
        }
    })
    //检验格式化数据
    $(":text[datatype]").each(function() {
        if ($('#' + $(this).attr('id') + '_error').length > 0) {
            if (typeof ($('#' + $(this).attr('id') + '_error').css('display')) != 'undefined' && $('#' + $(this).attr('id') + '_error').css('display') != 'none') {
                returnValue = false;
            }
        }
    })
    return returnValue;
}
//@Jquery扩展方法：
jQuery.fn.extend({//input_text_wrong,
    //@ShowWrongMessage:针对指定的文本框，添加信息错误提示的DIV，并显示
    //@如果文本框为必填项，则其在页面加载时肯定会自动生成必填项标识，在这个情况下，将会在此标识后边添加错误提示框
    ShowWrongMessage: function(msg) {
        var tmpid = $(this).attr('id');
        if (tmpid != null) {
            if ($('#' + tmpid + "_error").length == 0) {
                if ($('#' + tmpid + "_msg").length > 0) {
                    $('#' + tmpid + '_msg').after("<span id='" + tmpid + "_error' class='input_text_wrong' style='display:none;'>" + msg + "</span>");
                } else {
                    $(this).after("<span id='" + tmpid + "_error' class='input_text_wrong'>" + msg + "</span>");
                }
            }
            else {
                $('#' + tmpid + "_error").text(msg);
            }
            $('#' + tmpid + "_error").fadeIn().show();
        }
    },
    //@HideWrongMessage:针对指定的文本框，隐藏其信息错误提示的DIV
    HideWrongMessage: function() {
        var tmpid = $(this).attr('id');
        if (tmpid != null) {
            if ($('#' + tmpid + "_error").length > 0) {
                $('#' + tmpid + '_error').fadeOut().hide();
            }
        }
    },
    //@ValidateRegExp:针对指定的文本框，验证指定的正则表达式
    ValidateRegExp: function(req, value, msg, flag) {
        var result = false;
        if (value != null && value != "") {
            if (new RegExp(req).test(value) && flag) {
                $(this).attr('validated', true);
                $(this).HideWrongMessage();
                result = true;
            }
            else {
                $(this).attr('validated', false);
                $(this).ShowWrongMessage(msg);
                result = false;
            }
        }
        return result;
    },
    XinputTextOnKeyPressWithFloat: function(value, decimalDigits, msg) {
        var result = false;
        if (value != null && value != "") {
            var result = /[0-9.]/.test(value);
            if (result) {
                var pointIndex = value.indexOf('.');
                if (decimalDigits == null || decimalDigits == "") {
                    decimalDigits = 2;
                }
                if (pointIndex != -1) {
                    result = value.substring(pointIndex + 1).length <= parseInt(decimalDigits);
                }
                if (result) {
                    $(this).attr('validated', true);
                    $(this).HideWrongMessage();
                }
                else {
                    $(this).attr('validated', false);
                    $(this).ShowWrongMessage(msg);
                }
            }
            else {
                $(this).attr('validated', false);
                $(this).ShowWrongMessage(msg);
            }
        }
        return result;
    }
});
//页面初始化：根据属性加载相应事件
$(document).ready(function() {
    $(':text,:password').each(function() {
        var msg = "";
        $(this).attr('autocomplete', 'off');
        if ($(this).attr('errormessage') != null) {
            msg = $(this).attr('errormessage');
        }
        //去除左右空格
        if ($(this).attr('trim') != null) {
            $(this).bind('blur', function() {
                $(this).val($.trim($(this).val()));
            })
        }
        //必填项
        if ($(this).attr('required') != null) {
            $(this).after("<span id='" + $(this).attr('id') + "_msg' style='color:red;'>*</span>")//必填信息提示栏
            .bind('blur', function() {
                tmpValue = $(this).val();
                if (tmpValue == null || tmpValue == "") {
                    $(this).ShowWrongMessage(($_ERROR_MESSAGE.REQUIRED)); //必填信息
                    return false;
                }
                else {
                    $(this).HideWrongMessage();
                }
            });
        }
        //数据类型
        if ($(this).attr('datatype') != null) {
            //            $(this).css('ime-mode', 'disabled'); //关闭输入法
            //$(this).css('ime-mode', 'active'); //激活输入法
            var returnValue = false;
            switch ($(this).attr('datatype')) {
                case "int":
                    $(this).bind('keypress', function() {
                        inputTextOnKeyPressWithInt();
                    }).bind('paste', function() {
                        inputTextOnPaste();
                    }).bind('focus', function() {
                        value = $(this).val();
                        if ($.trim(value) != "") {
                            returnValue = $(this).ValidateRegExp($_REGEXP.INT, value, (msg != "" ? msg : $_ERROR_MESSAGE.INT), true);
                            if (returnValue == false) {
                                var empty = $(this).attr('empty');
                                if (empty && empty == 'true') {
                                    $(this).val('');
                                }
                            }
                        }
                    }).bind('blur', function() {
                        value = $(this).val();
                        var isRequired = $(this).attr('required');
                        if ($.trim(value) != "") {
                            returnValue = $(this).ValidateRegExp($_REGEXP.INT, $.trim(value), (msg != "" ? msg : $_ERROR_MESSAGE.INT), true);
                        } else {
                            if (typeof (isRequired) == 'undefined' || isRequired == false) {
                                $(this).HideWrongMessage();
                            }
                        }
                    })
                    break;
                case "float":
                    $(this).bind('keypress', function() {
                        value = $(this).val();
                        if ($.trim(value) != "") {
                            //获取是否有附加数据，附加数据中存放的是小数的位数
                            var dataattach = null;
                            if ($(this).attr('dataattach') != null) {
                                dataattach = $(this).attr('dataattach');
                            }
                            var decimalDigits = (dataattach == null ? 2 : dataattach);
                            inputTextOnKeyPressWithFloat(decimalDigits);
                        }
                    }).bind('paste', function() {
                        inputTextOnPaste();
                    }).bind('focus', function() {
                        value = $(this).val();
                        if ($.trim(value) != "") {
                            var dataattach = null;
                            if ($(this).attr('dataattach') != null) {
                                dataattach = $(this).attr('dataattach');
                            }
                            var decimalDigits = (dataattach == null ? 2 : dataattach);
                            returnValue = $(this).XinputTextOnKeyPressWithFloat(value, decimalDigits, $_ERROR_MESSAGE.FLOAT);
                            if (returnValue == false) {
                                var empty = $(this).attr('empty');
                                if (empty && empty == 'true') {
                                    $(this).val('');
                                }
                            }
                        }
                    }).bind('blur', function() {
                        value = $(this).val();
                        var isRequired = $(this).attr('required');
                        if ($.trim(value) != "") {
                            var dataattach = null;
                            if ($(this).attr('dataattach') != null) {
                                dataattach = $(this).attr('dataattach');
                            }
                            var decimalDigits = (dataattach == null ? 2 : dataattach);
                            returnValue = $(this).XinputTextOnKeyPressWithFloat(value, decimalDigits, $_ERROR_MESSAGE.FLOAT);
                        } else {
                            if (typeof (isRequired) == 'undefined' || isRequired == false) {
                                $(this).HideWrongMessage();
                            }
                        }
                    })
                    break;
                case "chinese":
                    $(this).bind('focus', function() {
                        $(this).css('ime-mode', 'active');
                        value = $(this).val();
                        if ($.trim(value) != "") {
                            returnValue = $(this).ValidateRegExp($_REGEXP.CHINESE, value, (msg != "" ? msg : $_ERROR_MESSAGE.CHINESE), true);
                            if (returnValue == false) {
                                var empty = $(this).attr('empty');
                                if (empty && empty == 'true') {
                                    $(this).val('');
                                }
                            }
                        }
                    }).bind('blur', function() {
                        value = $(this).val();
                        var isRequired = $(this).attr('required');
                        if ($.trim(value) != "") {
                            returnValue = $(this).ValidateRegExp($_REGEXP.CHINESE, value, (msg != "" ? msg : $_ERROR_MESSAGE.CHINESE), true);
                        } else {
                            if (typeof (isRequired) == 'undefined' || isRequired == false) {
                                $(this).HideWrongMessage();
                            }
                        }
                    })
                    break;
                case "english":
                    $(this).bind('focus', function() {
                        value = $(this).val();
                        if ($.trim(value) != "") {
                            returnValue = $(this).ValidateRegExp($_REGEXP.ENGLISH, value, (msg != "" ? msg : $_ERROR_MESSAGE.ENGLISH), true);
                            if (returnValue == false) {
                                var empty = $(this).attr('empty');
                                if (empty && empty == 'true') {
                                    $(this).val('');
                                }
                            }
                        }
                    }).bind('blur', function() {
                        value = $(this).val();
                        var isRequired = $(this).attr('required');
                        if ($.trim(value) != "") {
                            returnValue = $(this).ValidateRegExp($_REGEXP.ENGLISH, value, (msg != "" ? msg : $_ERROR_MESSAGE.ENGLISH), true);
                        } else {
                            if (typeof (isRequired) == 'undefined' || isRequired == false) {
                                $(this).HideWrongMessage();
                            }
                        }
                    })
                    break;
                case "email": //电子邮件
                    $(this).bind('focus', function() {
                        value = $(this).val();
                        if ($.trim(value) != "") {
                            returnValue = $(this).ValidateRegExp($_REGEXP.EMAIL, value, (msg != "" ? msg : $_ERROR_MESSAGE.EMAIL), true);
                            if (returnValue == false) {
                                var empty = $(this).attr('empty');
                                if (empty && empty == 'true') {
                                    $(this).val('');
                                }
                            }
                        }
                    }).bind('blur', function() {
                        value = $(this).val();
                        var isRequired = $(this).attr('required');
                        if ($.trim(value) != "") {
                            returnValue = $(this).ValidateRegExp($_REGEXP.EMAIL, value, (msg != "" ? msg : $_ERROR_MESSAGE.EMAIL), true);
                        } else {
                            if (typeof (isRequired) == 'undefined' || isRequired == false) {
                                $(this).HideWrongMessage();
                            }
                        }
                    })
                    break;
                case "mobile":
                    $(this).bind('keypress', function() { inputTextOnKeyPressWithInt(); }).bind('focus', function() {
                        value = $(this).val();
                        if ($.trim(value) != "") {//13...|15...
                            returnValue = $(this).ValidateRegExp($_REGEXP.MOBILE, value, (msg != "" ? msg : $_ERROR_MESSAGE.MOBILE), true);
                            if (returnValue == false) {
                                var empty = $(this).attr('empty');
                                if (empty && empty == 'true') {
                                    $(this).val('');
                                }
                            }
                        }
                    }).bind('blur', function() {
                        value = $(this).val();
                        var isRequired = $(this).attr('required');
                        if ($.trim(value) != "") {//13...|15...
                            returnValue = $(this).ValidateRegExp($_REGEXP.MOBILE, value, (msg != "" ? msg : $_ERROR_MESSAGE.MOBILE), true);
                        } else {
                            if (typeof (isRequired) == 'undefined' || isRequired == false) {
                                $(this).HideWrongMessage();
                            }
                        }
                    })
                    break;
                case "telephone":
                    //.bind('keypress', function() { inputTextOnKeyPressWithInt(); })
                    $(this).bind('focus', function() {
                        value = $(this).val();
                        if ($.trim(value) != "") {//13...|15...
                            returnValue = $(this).ValidateRegExp($_REGEXP.TELEPHONE, value, (msg != "" ? msg : $_ERROR_MESSAGE.MOBILE), true);
                            if (returnValue == false) {
                                var empty = $(this).attr('empty');
                                if (empty && empty == 'true') {
                                    $(this).val('');
                                }
                            }
                        }
                    }).bind('blur', function() {
                        value = $(this).val();
                        var isRequired = $(this).attr('required');
                        if ($.trim(value) != "") {
                            returnValue = $(this).ValidateRegExp($_REGEXP.TELEPHONE, value, (msg != "" ? msg : $_ERROR_MESSAGE.MOBILE), true);
                        } else {
                            if (typeof (isRequired) == 'undefined' || isRequired == false) {
                                $(this).HideWrongMessage();
                            }
                        }
                    })
                    break;
                case "sql":
                    //防SQL注入:不建议进行客户端防SQL注入，因为在客户端能够禁止JS运行。可能屏蔽掉
                    $(this).bind('blur', function() {
                        value = $(this).val();
                        if ($.trim(value) != "") {
                            var re = /^\?(.*)(select%20|insert%20|delete%20from%20|count\(|drop%20table|update%20truncate%20|asc\(|mid\(|char\(|XP_cmdshell|exec%20master|net%20localgroup%20administrators|\|:|net%20user|\|%20or%20)(.*)$/gi;
                            returnValue = $(this).ValidateRegExp(re, value.toLowerCase(), (msg != "" ? msg : $_ERROR_MESSAGE.SQL), false);
                        }
                    })
                    break;
                case "url":
                    var isRequired = $(this).attr('required');
                    if (isRequired && isRequired != null) {
                        var empty = $(this).attr('empty');
                        if (empty && empty == 'true') {
                            $(this).val("http://");
                            value = $(this).val();
                            var isRequired = $(this).attr('required');
                            if ($.trim(value) != "") {
                                var returnValue = $(this).ValidateRegExp($_REGEXP.URL, value.toLowerCase(), (msg != "" ? msg : $_ERROR_MESSAGE.URL), true);
                            } else {
                                if (typeof (isRequired) == 'undefined' || isRequired == false) {
                                    $(this).HideWrongMessage();
                                }
                            }
                        }

                    } else {
                        var empty = $(this).attr('empty');
                        if (empty && empty == 'true') {
                            $(this).val('');
                        }
                    }
                    $(this).bind('focus', function() {
                        value = $(this).val();
                        var isRequired = $(this).attr('required');
                        //如果是必填项，那么在获得焦点时，首先判断此文本框中数值是否通过正则验证
                        //如果通过验证，就不改变当前文本。如果没有通过验证，则将文本框赋值为http://
                        var returnValue = $(this).ValidateRegExp($_REGEXP.URL, value.toLowerCase(), (msg != "" ? msg : $_ERROR_MESSAGE.URL), true);
                        if (isRequired) {
                            if (!returnValue) {
                                var empty = $(this).attr('empty');
                                if (empty && empty == 'true') {
                                    $(this).val("http://");
                                }
                                var r = document.selection.createRange();
                                r.moveStart("character", $(this).val().length);
                                r.collapse();
                                r.select();
                            }
                        }
                        else {
                            if (!returnValue) {
                                var empty = $(this).attr('empty');
                                if (empty && empty == 'true') {
                                    $(this).val('');
                                }
                            }
                        }
                    }).bind('blur', function() {
                        value = $(this).val();
                        var isRequired = $(this).attr('required');
                        if ($.trim(value) != "") {
                            var returnValue = $(this).ValidateRegExp($_REGEXP.URL, value.toLowerCase(), (msg != "" ? msg : $_ERROR_MESSAGE.URL), true);
                        } else {
                            if (typeof (isRequired) == 'undefined' || isRequired == false) {
                                $(this).HideWrongMessage();
                            }
                        }
                    })
            } //switch end
        } //数据类型end
    })

})

