5

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?

1 Answer 1

6

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

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

Comments

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.