jhanink
8/23/2013 - 4:50 AM

on blur validation with rule

on blur validation with rule

/**
 * Take a validation function in parent scope passed in as the directive
 * attribute and handle appropriately.
 * validation function requires a scoped key to obtain the object's value
 * This can be the same as the model object. It's passed to the validation function
 *
 * <div validate-on-blur-with-rule="validateBid" key="bid_input_1001"></div>
 */
directives.directive('validateOnBlurWithRule', ['$parse', '$rootScope', '$timeout', function($parse, $rootScope, $timeout)
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
{
    return {
        link: function(scope, elm, attrs, ctrl) {
            elm.bind('blur', function() {
                var key = $parse(attrs.validationKey)(scope);
                var validationFunction = $parse(attrs.validateOnBlurWithRule)(scope);
                var isValid = validationFunction(key);
                if (!isValid) {
                    elm.addClass("gValidateFalse");
                    elm.css("border", "1px solid #C40C19");
                    elm.hide();
                    elm.fadeIn(500);
                } else {
                    elm.removeClass("gValidateFalse");
                    elm.css("border", "");
                }
                if(!scope.$$phase) {
                    scope.$apply();
                }
            });
        }
    };
}]);