Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular JS set form field as invalid

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?

like image 342
Levi Putna Avatar asked Jan 02 '14 00:01

Levi Putna


1 Answers

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

like image 96
angabriel Avatar answered Sep 21 '22 23:09

angabriel