Struggling to implement server-side form validation in an AngularJS app? Finding it tricky to invalidate a form field and show an error message?
Here's the setup of my app:
I have a model 'client' with a controller
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/"
});
});
Need help setting the abn field as invalid and displaying an error message? Looking for guidance on this issue.