2

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.

3
  • See docs.angularjs.org/guide/forms#custom-validation. You should be using c.$asyncValidators, not c.$parsers Commented Apr 21, 2015 at 1:32
  • Thanks for the link. The directive is called correctly and the setValidity function is also called. Could you please point out why above code is not working?, I had tried asyncValidators but result was same. I am going to to give a try with the link you provided but if you can point me what is wrong in the code above, it would be very helpful in clearing my doubt. Thanks again. Commented Apr 21, 2015 at 1:53
  • Have a look at the code example (script.js) under the Custom Validators link above. The username directive is similar to what you want. You simply need to return a promise Commented Apr 21, 2015 at 1:56

1 Answer 1

1

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;
    });
};
Sign up to request clarification or add additional context in comments.

3 Comments

Hi Phil, this code worked, I am accepting the answer. Thanks!... I was initially trying the server validation on the "Blur" event. I mean, the form should stay invalid until the value is returned as unique == true from the server. It will avoid continuous calls to server while user is typing in the field (currently happening). Could you please help me to achieve the same? Thanks!
@JVM Still working on decent server-side validation on submit myself. I'm not a fan of the continuous validation style that Angular promotes. There's some ideas in this post ~ stackoverflow.com/questions/12864887/…
I used "debounce" for the fields I need to check with server and it helped. It is letting me finish the typing and then makes a server call, working similar to blur event. ng-model-options="{ debounce: 500 }"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.