<p>This is a step by step guide for Server Side form validations with AngularJS and Rails backend</p>
<p>Most of the information comes from the following article but I add some important information that was left out:</p>
<p><a href="http://codetunes.com/2013/server-form-validation-with-angular/">Server Form Validation with Angular.js</a></p>
<p>We will start with the form:</p>
angular.module('yourApp').controller('PostCtrl', function($scope, PostService) {
$scope.addPost = function() {<br /> var error, success, newPost;
newPost = $scope.newPost;
$scope.errors = {}; //clean up previous server errors
success = function(result) {
//things to do if it returns success, here is my example code, will likely be different for you
$scope.posts.unshift(result);
$scope.newPost = {};
};
error = function(result) {
angular.forEach(result.data.errors, function(errors, field) {
$scope.yourForm[field].$setValidity('server', false);
$scope.errors[field] = errors.join(', ');
});
};
// if you are using $http in your server do this
// return PostService.create(post).then(success, error);
// otherwise if you are using $resource in your service do this
// return PostService.save(post).$promise.then(success, error);
};
});
<p>Lastly we will change your models Rails Controller so that it returns the errors as json:</p>
if @phrase.save
render json: @phrase, status: 200
else
render json: {errors: @phrase.errors}, status: 422
end
<p>You now have server side validation! Congrats!</p>