7

I am new to angular.js

 <input type="email" disabled='disabled' name="email" ng-model="userInfo.emailAddress" 
                                    class="input-xlarge settingitem" style="height:30px;"> 

<span ng-show="myForm.email.$error.email" class="help-inline" style="color:red;font-size:10px;">
                                        Not a Valid Email Address</span>

I have email field, corresponding to which i need to check at server if it already exists in database or not.

Can anyone guide me through the steps how it can be done using angular directives and services for checking at server

1 Answer 1

9

I would suggest writing a directive that would plug into NgModelController#$parsers pipeline (check "Custom Validation" from http://docs.angularjs.org/guide/forms).

Here is a sketch of such a directive:

.directive('uniqueEmail', ["Users", function (Users) {
  return {
    require:'ngModel',
    restrict:'A',
    link:function (scope, el, attrs, ctrl) {

      //TODO: We need to check that the value is different to the original

      //using push() here to run it as the last parser, after we are sure that other validators were run
      ctrl.$parsers.push(function (viewValue) {

        if (viewValue) {
          Users.query({email:viewValue}, function (users) {
            if (users.length === 0) {
              ctrl.$setValidity('uniqueEmail', true);
            } else {
              ctrl.$setValidity('uniqueEmail', false);
            }
          });
          return viewValue;
        }
      });
    }
  };
}])

Where the Users.query is an async call to check if an email is unique or not. Of course you should substitute this with a call to your back-end.

When done, this directive can be used like so:

<input type="email" ng-model="user.email" unique-email>

Example of this directive was taken from the angular-app that some of the AngularJS community members try to put together to illustrate common use-cases. It might be worth checking out to see how all this fits together in the complete app.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your answer, Can you please also suggest how to compare the previous value.
your solution is working fine, but i am facing one issue, when i get a callback from server, my whole form gets clear
How do you call from server?

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.