angular-auto-validate icon indicating copy to clipboard operation
angular-auto-validate copied to clipboard

request/potential bug: allow validation when on $touched instead of on $dirty

Open crhistianramirez opened this issue 7 years ago • 1 comments

currently only validates when input is $dirty (after user types something in and leaves input)

Would be nice if it would validate when a user touched a required input, left it blank, and moved to another input

I tried creating a custom directive to set any $touched input to $dirty but there seems to be a bug where it only succeeds if that is set in the first ~2 seconds. Not sure if this is a bug with angular or this library.

My simple directive:

    return {
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, elem, attrs, form){
            scope.$watch(function(){
                return form.$touched;
            }, function(wasTouched, oldVal){
                if(wasTouched){
                    form.$setDirty();
                }
            });
        }
    }

crhistianramirez avatar Sep 08 '17 15:09 crhistianramirez

Here's a work-around I came up with. a bit hacky but it does the trick. We use underscore and have full jquery but I'm sure if anyone needs this they can figure out how to edit it to work for them.

function noEmptyFieldsDirective(){
    return {
        restrict: 'A',
        replace: true,
        require: '^form',
        scope: {
            noEmptyFields: '@' //optionally pass list of input names that wont be restricted
        },
        link: function(scope, element, attrs, form){
            element.find(':input').each(function(){
                var input = $(this);
                var blacklist = scope.noEmptyFields ? scope.noEmptyFields.replace(/ /g, '').split(',') : '';
                var isInput = _.contains(['text', 'password', 'email'], input.attr('type'));
                if(isInput && !_.contains(blacklist, input[0].name)){
                    input.focus(function(){
                        //add and remove a character to trick auto-validate into
                        //thinking user entered data and left field empty
                        var snapshot = form[input[0].name].$viewValue;
                        form[input[0].name].$setViewValue(snapshot ? snapshot + ' ' : ' ');
                        form[input[0].name].$setViewValue(snapshot ? snapshot : '');
                    });
                }
            });
        }
    };
}

crhistianramirez avatar Sep 08 '17 19:09 crhistianramirez