Skip to content
This repository has been archived by the owner on Aug 15, 2021. It is now read-only.

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

Open
crhistianramirez opened this issue Sep 8, 2017 · 1 comment

Comments

@crhistianramirez
Copy link

crhistianramirez commented Sep 8, 2017

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 crhistianramirez changed the title request: allow validation when on $touched instead of on $dirty request/potential bug: allow validation when on $touched instead of on $dirty Sep 8, 2017
@crhistianramirez
Copy link
Author

crhistianramirez commented Sep 8, 2017

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 : '');
                    });
                }
            });
        }
    };
}

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant