Reputation: 38142
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?
Upvotes: 0
Views: 1336
Reputation: 18055
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.
Upvotes: 2
Reputation: 2211
<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.
Upvotes: 0
Reputation: 8307
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.
Upvotes: 1