a.js - norberthu30/jQuery-Validation-For-Twitter-Bootstrap-Tooltip GitHub Wiki

/**

  • @author GeekTantra

  • @date 20 September 2009

  • http://www.geektantra.com/2009/09/jquery-live-form-validation/

  • Modified by ddarren: added support for twitter boostrap

  • https://github.com/ddarren/jQuery-Live-Form-Validation-For-Twitter-Bootstrap */ (function(jQuery){ var ValidationErrors = new Array(); jQuery.fn.validate = function(options){ options = jQuery.extend({ expression: "return 0;", message1: "",
    error_container_class: "control-group", live: true }, options); var SelfID = jQuery(this).attr("id");

     // getting unix_time to make a unique id for form if the form doesn't already have an one
     var unix_time = new Date();
     unix_time = parseInt(unix_time.getTime() / 1000);
     //give the form an id if it doesn't already have one
     if (!jQuery(this).parents('form:first').attr("id")) {
         jQuery(this).parents('form:first').attr("id", "Form_" + unix_time);
     }
     var FormID = jQuery(this).parents('form:first').attr("id");
     if (!((typeof(ValidationErrors[FormID]) == 'object') && (ValidationErrors[FormID] instanceof Array))) {
         ValidationErrors[FormID] = new Array();         
         ValidationErrors[FormID+"func"] = $.Callbacks();         
     }
     if (options['live']) {
         // if the passed in element is a container with inputs
     	
         if (jQuery(this).find('input').length > 0) {
             // once an input loses focus, run validation
             jQuery(this).find('input').bind('blur', function(){
                 if (validate_field("#" + SelfID, options)) {
                     if (options.callback_success) 
                         options.callback_success(this);
                 }else {
                     if (options.callback_failure) 
                         options.callback_failure(this);
                 }
             });
             // remove error message once an input is focused on 
             jQuery(this).find('input').bind('focus keypress click', function(){
     			var ei = jQuery("#" + SelfID).data("ei");
     			if(ei){
     				ei.tooltip('destroy');
     				jQuery("#" + SelfID).data("ei",null);
     			}	
                 jQuery("#" + SelfID).parents("." + options['error_container_class']).removeClass('error');
             });
         }else { // if the passed in element is input to validate itselft
             // when  the input loses focus, validate
             jQuery(this).bind('blur', function(){
                 validate_field(this);
             });
             // when the input gains focused remove error message
             jQuery(this).bind('focus keypress', function(){
                 var jQueryObjectBeforeErrorMessage = jQuery(this); 
     			var ei = jQueryObjectBeforeErrorMessage.data("ei");
     			if(ei){				
     				ei.tooltip('destroy');
     				jQuery("#" + SelfID).data("ei",null);
     			}	
    
     			jQuery(this).parents("." + options['error_container_class']).removeClass('error');
             });
         }
     }
     // perform validation when form is submitted - needed by both live and non-live validation		
     ValidationErrors[FormID+"func"].add( function(){		
         if (!validate_field('#' + SelfID)) {
     		$("#"+FormID).data("rv",false);				
     	}
     });		
     
     // function that does the actual validation
     function validate_field(id){
         var self = jQuery(id).attr("id");
         var expression = 'function Validate(){' + options['expression'].replace(/VAL/g, 'jQuery(\'#' + self + '\').val()') + '} Validate()';
         var validation_state = eval(expression);
     	
     	var jQueryObjectBeforeErrorMessage = jQuery(id); 
     	var ei = jQueryObjectBeforeErrorMessage.data("ei");
     	
         if (validation_state>0) {
         	var before_error = jQueryObjectBeforeErrorMessage.data("berror");
             if (!ei) {
     			ei =jQueryObjectBeforeErrorMessage.tooltip({title:options['message'+validation_state],placement:'right',trigger:"manual"}).tooltip('show');
     			jQueryObjectBeforeErrorMessage.data("ei",ei);
     			jQueryObjectBeforeErrorMessage.data("berror",validation_state);
                 jQuery(id).parents("div." + options['error_container_class']).addClass('error');
             }else if(validation_state != before_error){
             	ei.tooltip('destroy');
             	ei =jQueryObjectBeforeErrorMessage.tooltip({title:options['message'+validation_state],placement:'right',trigger:"manual"}).tooltip('show');
     			jQueryObjectBeforeErrorMessage.data("ei",ei);
     			jQueryObjectBeforeErrorMessage.data("berror",validation_state);
             }
    
             if (ValidationErrors[FormID].join("|").search(id) == -1) 
                 ValidationErrors[FormID].push(id);
             return false;
         }else {
     		if(ei){				
     			ei.tooltip('destroy');
     			jQueryObjectBeforeErrorMessage.data("ei",null);
     		}
     	
             for (var i = 0; i < ValidationErrors[FormID].length; i++) {
                 if (ValidationErrors[FormID][i] == id) 
                     ValidationErrors[FormID].splice(i, 1);
             }
             return true;
         }
     }
    

    };
    jQuery.fn.validated = function(){ var FormID = jQuery(this).attr("id"); jQuery("#"+FormID).data("rv",true); ValidationErrors[FormID+"func"].fire(); return jQuery("#"+FormID).data("rv");

    }; })(jQuery);

var pub_v ={ isChecked:function(id){ var ReturnVal = 1; $("#" + id).find('input[type="radio"]').each(function(){ if ($(this).is(":checked")) ReturnVal = 0; });

	    $("#" + id).find('input[type="checkbox"]').each(function(){
	        if ($(this).is(":checked")) 
	            ReturnVal = 0;
	    });	
	    return ReturnVal;
	},
	empty:function(id,max){			
		var me =$("#"+id);
		var v = me.val();
		if(!v|| $.trim(v)=="")
			return 1;
		if(max){
			 v = $.trim(v);
			var len  = pub_v._getLen(v);				
			if( len > max)
				return 2;
		}
		return 0;
	},
	phone:function(id,max){
		var r = pub_v.empty(id,max);
		if(r>0)
			return r;
					
		var reg = /^(\d|\-|\(|\)|\+)\d|\-|\(|\)|\+{7,12}$/gi;
		var me =$("#"+id);
		var v = me.val();
		if(reg.test(v))
			return 0;
		return 3;
	},
	mail:function(id){			
		var me =$("#"+id);
		var v = me.val();
		if(!v|| $.trim(v)=="")
			return 1;
		
		var reMail =  /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		if(reMail.test(v))
			return 0;
		return 2;
	},
	range:function(id,min,max){			
		var me =$("#"+id);
		var v = $.trim(me.val()+"");
		if(v.length>=min && v.length <= max)
			return 0;
		return 1;
	},
	max:function(id,max){			
		var me =$("#"+id);
		var v = $.trim(me.val()+"");
		var len  = pub_v._getLen(v);
		if( len > max)
			return 1;
		return 0;
	},
	min:function(id,m){			
		var me =$("#"+id);
		var v = $.trim(me.val()+"");
		var len  = pub_v._getLen(v);
		if( len < m)
			return 1;
		return 0;
	},
	_getLen:function(val) {
		if(typeof val != "string") return 0;
		
		var len = 0; 
		var c;			
		for (var i = 0; i < val.length; i++) {
			c = val.charAt(i);
			if (c.match(/[^\x00-\xff]/ig) != null){ 
				len += 2; 
			}else{ 
				len += 1;
			}				
		} 
		return len/2; 
	} 

};