0

My questions is similar to Form Validation with Dependent Fields in AngularJS however the validation has to be done on the server side with Ajax.

I have two fields city and postal code and want to use a backend service to tell if both fields match.
The backend service has already been implemented. So now I am trying to integrate the service with angular.

Any suggestions?

4 Answers 4

2

have a look at ui-validate from angular-ui. you can use ui-validate with a function call returning promise

so your html would be

      <input type="text" ng-model="city" ui-validate=" 'doMatch($value, postal)' ">
      <input type="text" ng-model="postal" ui-validate=" 'doMatch(city, $value)' ">

and the js should be

$scope.doMatch = function(c, p) {
     return $http.post("/api/validateCityPostal", {postal: p, city : c});
}

note that above function is returning a promise. and from server you should return success/failure to have $valid or $invalid on the ui-validate.

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

1 Comment

This looks realy nice
1

AngularJS 1.3 introduced async validators. You can add a function that returns a promise to your ngModelController's $asyncValidators array, it will set the model's validity based on the value the promise is resolved with.

If you can't use 1.3 then you could always set the model to be invalid while the request is happening and set it to its final value once you get the result back from the server.

In either case the custom directive approach in the answer you linked to is probably your best bet.

1 Comment

Unfortunately I have to use 1.2. I guess this is the way to go for me I was hoping for a better solution but this will be good enough ;)
0
<form action="blablabla">
   <input type="text" ng-model="city">
   <input type="text" ng-model="postal">
</form>

JS:

 angular.module("module",[]).service("validate", ['$http', function ($http){
       this.validate_postal = function (p) {
           return $http.post("/api/validate_post", {post: p});
       }

       this.validate_city= function (c){
            return $http.post("/api/city",{city: city});
       }

}]);

Validation service returns promise. So you can add async callbacks latter in the controller.

1 Comment

Unfortunately I have to submit both in one request - the postal code and the city
-1

There is a great example here. "Custom validations" section

1 Comment

that example does not deal with multiple dependent fields

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.