对我佛山人的通用form校验代码的小改动

/*************************************************
 * Validator v1.0
 * @author 我佛山人
 * [email protected]
 * http://www.cunite.com
 *
 * @author Sam Chen(我非佛山人,乃江西景德镇人也)
 * [email protected]
 ************************************************/
FormValidator = {
    Require : /.+/,
    
    // Modified by S.C. on 06/27/2009 00:08
    //Email : /^\w+([-+.]\w+)*@\w+([-.]\\w+)*\.\w+([-.]\w+)*$/,
    Email : /^([\w]+)(.[\w]+)*@([\w-]+\.){1,5}([A-Za-z]){2,4}$/,
    
    Phone : /^((\(\d{3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}$/,
    Mobile : /^((\(\d{3}\))|(\d{3}\-))?13\d{9}$/,
    
    // Modified by S.C. on 06/30/2009 13:01
    //Url : /^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/,
    Url : /(((https?)|(ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i,
    
    IdCard : /^\d{15}(\d{2}[A-Za-z0-9])?$/,
    Currency : /^\d+(\.\d+)?$/,
    Number : /^\d+$/,
    Zip : /^[1-9]\d{5}$/,
    QQ : /^[1-9]\d{4,8}$/,
    Integer : /^[-\+]?\d+$/,
    Double : /^[-\+]?\d+(\.\d+)?$/,
    English : /^[A-Za-z]+$/,
    Chinese : /^[\u0391-\uFFE5]+$/,
    UnSafe : /^(([A-Z]*|[a-z]*|\d*|[-_\~!@#\$%\^&\*\.\(\)\[\]\{\}<>\?\\\/\'\"]*)|.{0,5})$|\s/,
    IsSafe : function(str){return !this.UnSafe.test(str);},
    SafeString : "this.IsSafe(value)",
    Limit : "this.limit(value.length,getAttribute('min'), getAttribute('max'))",
    LimitB : "this.limit(this.LenB(value), getAttribute('min'), getAttribute('max'))",
    //Date : "this.IsDate(value, getAttribute('min'), getAttribute('format'))",
    Date : "this.isDate(value, getAttribute('format'), getAttribute('minValue'), getAttribute('maxValue'))",
    Repeat : "value == document.getElementsByName(getAttribute('to'))[0].value",
    Range : "getAttribute('min') < value && value < getAttribute('max')",
    Compare : "this.compare(value,getAttribute('operator'),getAttribute('to'))",
    
    // Added by Sam Chen on 06/26/2009 00:41
    CompareWithAnotherElement : "this.compareWithAnotherElement(value,getAttribute('operator'),document.getElementById(getAttribute('to')).value)",
    
    Custom : "this.Exec(value, getAttribute('regexp'))",
    Group : "this.MustChecked(getAttribute('name'), getAttribute('min'), getAttribute('max'))",
    ErrorItem : [document.forms[0]],
    ErrorMessage : ["以下原因导致提交失败:\t\t\t\t"],
    /**
     * validate a field typically when it loses the focus (onblur)
     * @author Sam Chen
     */
    validateField : function(theField, mode) {
    	var errorMsg = '';
    	with(theField){
    		value = value.trim();  // Added by S.C. on 06/24/2009 21:09
            var _dataType = getAttribute("dataType");
            if(typeof(_dataType) == "object" || typeof(this[_dataType]) == "undefined") {
            	// do nothing
            } else {
            	this.ClearState(theField);
            	
            	if ((_dataType == 'Require' || getAttribute('require') == 'true') && value == '') {
            		errorMsg = getAttribute('blankText')||'该项必须输入';
            	} else {
            		if(getAttribute("require") != "false" || value != "") {
		            	switch(_dataType){
			                case "Date" :
			                case "Repeat" :
			                case "Range" :
			                case "Compare" :
			                
			                // Added by S.C. on 06/28/2009 00:44
			                case "CompareWithAnotherElement" :
			                
			                case "Custom" :
			                case "Group" :
			                case "Limit" :
			                case "LimitB" :
			                case "SafeString" :
			                    if(!eval(this[_dataType])) {
			                        errorMsg = getAttribute("msg");
			                    }
			                    break;
			                default :
			                    if(!this[_dataType].test(value)){
			                        errorMsg = getAttribute("msg");
			                    }
			                    break;
			            }
		            }
            	}
            }
            
        }
        if(errorMsg != ''){
            mode = mode || 3;//1;
            switch(mode){
                case 2 :
                    theField.style.color = "red";
                case 1 :
                    alert(errorMsg);
                    theField.focus();
                break;
                case 3 :
                    try{
                    	var span = document.createElement("SPAN");
                        span.id = "__ErrorMessagePanel";
                        span.style.color = "red";
                        //span.style.cursor = 'pointer';
                        span.style.cursor = 'help';
                        
                        //theField.parentNode.appendChild(span);
                        var parentNode = theField.parentNode;
                        while (parentNode.nodeName != 'TD') {
                        	parentNode = parentNode.parentNode;
                        }
                        parentNode.appendChild(span);
                        
                        span.innerHTML = ' ×';
                        span.title = errorMsg;
                    } catch(e){alert(e.description);}
                    //theField.focus();
                    break;
                default :
                    alert(errorMsg.join("\n"));
                    break;
            }
            return false;
        }
        return true;
        
    },
    validateForm : function(theForm, mode){
        var obj = theForm || event.srcElement;
        var count = obj.elements.length;
        this.ErrorMessage.length = 1;
        this.ErrorItem.length = 1;
        this.ErrorItem[0] = obj;
        for(var i=0;i 1){
            mode = mode || 3;//1;
            var errCount = this.ErrorItem.length;
            switch(mode){
                case 2 :
                    for(var i=1;i
//                        var span = document.createElement("SPAN");
//                        span.id = "__ErrorMessagePanel";
//                        span.style.color = "red";
//                        this.ErrorItem[i].parentNode.appendChild(span);
//                        span.innerHTML = this.ErrorMessage[i].replace(/\d+:/,"*");
                    	var span = document.createElement("SPAN");
                        span.id = "__ErrorMessagePanel";
                        span.style.color = "red";
                        //span.style.cursor = 'pointer';
                        span.style.cursor = 'help';
                        
                        //this.ErrorItem[i].parentNode.appendChild(span);
                        var parentNode = this.ErrorItem[i].parentNode;
                        while (parentNode.nodeName != 'TD') {
                        	parentNode = parentNode.parentNode;
                        }
                        parentNode.appendChild(span);
                        
                        span.innerHTML = ' ×';
                        span.title = this.ErrorMessage[i].replace(/\d+:/,"");
                        // Code modified by S.C. on 06/24/2009 14:03 <==
                    }
                        catch(e){alert(e.description);}
                    }
                    //this.ErrorItem[1].focus();
                    break;
                default :
                    alert(this.ErrorMessage.join("\n"));
                    break;
            }
            return false;
        }
        return true;
    },
    limit : function(len,min, max){
        min = min || 0;
        max = max || Number.MAX_VALUE;
        return min <= len && len <= max;
    },
    LenB : function(str){
        return str.replace(/[^\x00-\xff]/g,"**").length;
    },
    ClearState : function(elem){
    	// Modified by Sam Chen ==>
//        with(elem){
//            if(style.color == "red") style.color = "";
//            var lastNode = parentNode.childNodes[parentNode.childNodes.length-1];
//            if(lastNode.id == "__ErrorMessagePanel") parentNode.removeChild(lastNode);
//        }
        var parentNode = elem.parentNode;
        while (parentNode.nodeName != 'TD') {
        	parentNode = parentNode.parentNode;
        }
        var lastNode = parentNode.childNodes[parentNode.childNodes.length-1];
        if(lastNode.id == "__ErrorMessagePanel") parentNode.removeChild(lastNode);
        // Modified by Sam Chen <==
    },
    /**
     * clear all the error messages
     * @author Sam Chen
     */
    clearErrorMsg : function(theForm) {
    	var obj = theForm || event.srcElement;
    	var count = obj.elements.length;
    	for(var i=0;i op2);
            case "GreaterThanEqual":
                return (op1 >= op2);
            case "LessThan":
                return (op1 < op2);
            case "LessThanEqual":
                return (op1 <= op2);
            default:
                return (op1 == op2);
        }
    },
    
    // Added by S.C. on 06/28/2009 00:43
    compareWithAnotherElement: function(op1,operator,op2){
        switch (operator) {
            case "NotEqual":
                return (op1 != op2);
            case "GreaterThan":
                return (new Number(op1) > new Number(op2));
            case "GreaterThanEqual":
                return (new Number(op1) >= new Number(op2));
            case "LessThan":
                return (new Number(op1) < new Number(op2));
            case "LessThanEqual":
                return (new Number(op1) <= new Number(op2));
            default:
                return (op1 == op2);
        }
    },
    
    MustChecked : function(name, min, max){
        var groups = document.getElementsByName(name);
        var hasChecked = 0;
        min = min || 1;
        max = max || groups.length;
        for(var i=groups.length-1;i>=0;i--)
            if(groups[i].checked) hasChecked++;
        return min <= hasChecked && hasChecked <= max;
    },
    
    /**
     * @deprecated (annotated by Sam Chen -- I didn't understand this code fragment, 
     * so I just replaced it with another method isDate)
     */
    IsDate : function(op, formatString){
        formatString = formatString || "ymd";
        var m, year, month, day;
        switch(formatString){
            case "ymd" :
                m = op.match(new RegExp("^\\s*((\\d{4})|(\\d{2}))([-./])(\\d{1,2})\\4(\\d{1,2})\\s*$"));
                if(m == null ) return false;
                day = m[6];
                month = m[5]--;
                year = (m[2].length == 4) ? m[2] : GetFullYear(parseInt(m[3], 10));
                break;
            case "dmy" :
                m = op.match(new RegExp("^\\s*(\\d{1,2})([-./])(\\d{1,2})\\2((\\d{4})|(\\d{2}))\\s*$"));
                if(m == null ) return false;
                day = m[1];
                month = m[3]--;
                year = (m[5].length == 4) ? m[5] : GetFullYear(parseInt(m[6], 10));
                break;
            default :
                break;
        }
        var date = new Date(year, month, day);
        return (typeof(date) == "object" && year == date.getFullYear() && month == date.getMonth() && day == date.getDate());
        function GetFullYear(y){return ((y<30 ? "20" : "19") + y)|0;}
    
    }
    /**
     * Code added by S.C. on 06/26/2009 21:05
     * is it a valid date?
     */
    ,isDate : function(value, format, minValue, maxValue) {
    	value = this.parseDate(value, format);
        if(!value){
            return false;
        }
        var time = value.getTime();
        if(minValue && time < this.parseDate(minValue, format).getTime()){
            return false;
        }
        if(maxValue && time > this.parseDate(maxValue, format).getTime()){
            return false;
        }
        return true;
    }
    /**
     * Code added by S.C. on 06/26/2009 21:16
     * integrated with ExtJS
     */
    ,parseDate : function(value, format){
        if(!value || Ext.isDate(value)){
            return value;
        }
        return Date.parseDate(value, format);
    }
};
 

你可能感兴趣的:(对我佛山人的通用form校验代码的小改动)