Search code examples
angularjsangularjs-directiveangular-validation

Validate that 2 angular Form fields do not have the same content


I have an angular form consisting of two fields location A and Location B. What I'd like to achieve is a directive that compares both fields and validates accordingly, style the valid or invalid field appropriately whenever the fields have the same location.

I have attempted inserting logic using ng-change = validateLocations() but based on what i've researched, a directive would be better suited for scenarios such is the above.The same logic could also be applied in validating from and to dates on a datepicker as well.

I tried something like this:

.directive("locationANotEqual", function () {

        return {

            restrict: "A",
           require: "ngModel",
            link: function (scope, element, attr, ctrl) {

                ctrl.$validators.locationNotEqual= function (modelvalue) {
                    if (modelvalue !== scope.form.locationB) {
                        return true;

                    } else {

                        return false
                    }
                }
}
}
});

I put the attribute on the locationA input field in this regard. What I'd like is to be able to incorporate checks for both fields in a single directive rather than 2.


Solution

  • Add another parameter to your directive and compare to that value instead of scope.form.locationB. Call attributes.$observe on that value for changes so the model of the directive can be marked valid/invalid.

    data-ng-model-options="{allowInvalid: true}" is used so that when the values do match, the model is still set.

    app.directive('validateNotEqual', [
        function() {
            return {
                restrict: 'AE',
                require: '^ngModel',
                link: function(scope, element, attributes, ngModelCtrl) {
                    if (!ngModelCtrl) {
                        return;
                    }
    
                    var errorKey = 'notEqual';
    
                    ngModelCtrl.$validators[errorKey] = function(value) {
                        return value !== attributes.validateNotEqual;
                    };
    
                    attributes.$observe('validateNotEqual', function(value) {
                        ngModelCtrl.$setValidity(
                            errorKey,
                            value !== ngModelCtrl.$modelValue);
                    });
                }
            };
        }
    ]);
    

    See plunker.