javascript Angular JS 将表单字段设置为无效

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20874665/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 19:31:14  来源:igfitidea点击:

Angular JS set form field as invalid

javascriptangularjs

提问by Levi Putna

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.

我正在尝试向我的 angular js 应用程序添加一些服务器端表单验证。我很难使表单字段无效并显示错误消息。

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?

有人能够为我提供一个示例,说明我应该如何将 abn 字段设置为无效并显示错误消息?

回答by angabriel

The way to display the error should be like this:

显示错误的方式应该是这样的:

changed from $error.serverto $invalid:

更改$error.server$invalid

<span ng-show="form.abn.$invalid">{{client.errors.abn}}</span>

I added a style for ng-invalidclass 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.errorsbecause it was null.

我为ng-invalid类添加了一个样式并创建了一个 plunkr,一旦您按下保存按钮,该字段将变为红色并显示错误消息。设置属性时还有另一个错误,$scope.errors因为它为空。

http://plnkr.co/fDWF5g

http://plnkr.co/fDWF5g