I am trying to add some server side form validation to my angular js app. I'm having a hard time invalidating the form field and displaying the error message.
My basic application looks like this:
I have a model 'client' with a controler
Accounts.controller('Client', ['$scope', 'ClientService', function ($scope, ClientService) {
$scope.loading = false;
$scope.errors = null;
$scope.init = function () {
$scope.abn = "some value from API call";
};
$scope.save = function (client) {
$scope.form.abn.$setValidity("server", false);
$scope.errors.abn = "Error message";
}
$scope.init();
}]);
and a form view
<form name="form">
<div class="form-group">
<label>ABN Number</label>
<input type="text" name="abn" ng-model="client.abn">
<span ng-show="form.abn.$error.server">{{client.errors.abn}}</span>
</div>
<button ng-click="save(client)">Save</button>
</form>
and an app like so
var Accounts = angular.module('Accounts', [
'ngRoute',
'ui.select2',
'ui.router'
])
.config(function ($stateProvider, $routeProvider) {
$routeProvider.otherwise('/404');
$stateProvider
.state('client', {
url: "/client",
templateUrl: "client",
controller: 'Client'
})
.state('404', {
url: "/404",
templateUrl: "/error/e404/"
});
});
Is someone able to provide me with an example of how I should be setting the abn field as invalid and displaying an error message?
The way to display the error should be like this:
changed from $error.server
to $invalid
:
<span ng-show="form.abn.$invalid">{{client.errors.abn}}</span>
I added a style for ng-invalid
class and created a plunkr where the field gets red and the errorMessage is displayed, once you press the save button. There was also another error when setting a property on $scope.errors
because it was null.
http://plnkr.co/fDWF5g
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With