Search code examples
angularjsangularjs-directivedirectivecustom-validatorsangularjs-ng-form

Angularjs $setValidity is not blocking Form Submission when set to false.. whats wrong here?


I have a directive "ensureUniqueValidator" for checking uniqueness of values in database. The function is generic. It is called in the HTML page in the following way:

<input type="email" name="email" ng-model="userCtrl.user.email" 
required ensure-unique-validator />

Directive Code:

    app.directive('ensureUniqueValidator', [
        '$http',
        function($http) {
            return {
                restrict : 'A',
                require : 'ngModel',
                link : function(scope, ele, attrs, c) {

                    c.$parsers.push(function(val) {

                        return $http.get(
                                'MainServlet.do?method=is' + attrs.name
                                        + 'unique&' + attrs.name + '='
                                        + val).then(
                                function(result) {
                                    console.log(result.data);
                                    c.$setValidity('ensureUniqueValidator',
                                            result.data);
                                    return result.data;//returns true or false
                                });
                    });
                }
            }
        } ]);

Problem is, the Form remains valid even if server has returned as False. Looks like, the $setValidity function is not invalidating the Form.

Am I doing something wrong here? Thanks in advance.


Solution

  • This should work (according to the docs anyway, I haven't written one of these yet).

    The main thing seems to be that the promise should either resolve for a valid value or reject for an invalid one.

    // don't forget to inject the $q service
    c.$asyncValidators.ensureUniqueValidator = function(modelValue, viewValue) {
        if (ctrl.$isEmpty(modelValue)) {
            // consider empty model valid
            return $q.when();
        }
    
        var params = {
            method: 'is' + attrs.name + 'unique'
        };
        params[attrs.name] = modelValue;
    
        return $http.get('MainServlet.do', {
            params: params
        }).then(function(response) {
            if (!response.data) {
                return $q.reject();
            }
            return true;
        });
    };