72

我正在使用 Angular 和 Bootstrap。这是供参考的代码:

<form name="newUserForm" ng-submit="add()" class="" novalidate>
    <input type="text" class="input" ng-model="newUser.uname" placeholder="Twitter" ng-pattern="/^@[A-Za-z0-9_]{1,15}$/" required></td>
    <button type="submit" ng-disabled="newUserForm.$invalid" class="btn btn-add btn-primary">Add</button>
</form>

Bootstrap 具有无效字段的样式,格式为input:invalid {.... }; 当字段为空时,这些会启动。现在我还通过 Angular 进行了一些模式匹配。这会在 ":invalid" 关闭但 ".ng-invalid" 开启时产生奇怪的情况,这将需要我为 ".ng-invalid" 类重新实现引导 CSS 类。

我看到两个选项,但都遇到了问题

  • 让 Angular 使用一些自定义类名而不是“ng-valid”(我不知道该怎么做)。
  • 禁用 html5 验证(我认为这就是表单标签中的“novalidate”属性应该做的,但由于某种原因无法让它工作)。

那里的 Angular-Bootstrap 指令不包括样式。

4

12 回答 12

92

使用 Bootstrap 的“错误”类进行样式设置。您可以编写更少的代码。

<form name="myForm">
  <div class="control-group" ng-class="{error: myForm.name.$invalid}">
    <label>Name</label>
    <input type="text" name="name" ng-model="project.name" required>
    <span ng-show="myForm.name.$error.required" class="help-inline">
        Required</span>
  </div>
</form>

编辑: 正如其他答案和评论指出的那样 - 在 Bootstrap 3 中,该类现在是“有错误”,而不是“错误”。

于 2013-02-19T09:08:13.470 回答
47

Bootstrap 3 中的类已更改:

<form class="form-horizontal" name="form" novalidate ng-submit="submit()" action="/login" method="post">
  <div class="row" ng-class="{'has-error': form.email.$invalid, 'has-success': !form.email.$invalid}">
    <label for="email" class="control-label">email:</label>
    <div class="col">
    <input type="email" id="email" placeholder="email" name="email" ng-model="email" required>
    <p class="help-block error" ng-show="form.email.$dirty && form.email.$error.required">please enter your email</p>
    <p class="help-block error" ng-show="form.email.$error.email">please enter a valid email</p>
  ...

注意周围的引号'has-error''has-success': 花了一段时间才找到...

于 2013-06-25T20:22:23.433 回答
34

另一种解决方案:创建has-error根据子输入切换类的指令。

app.directive('bsHasError', [function() {
  return {
      restrict: "A",
      link: function(scope, element, attrs, ctrl) {
          var input = element.find('input[ng-model]'); 
          if (input.length) {
              scope.$watch(function() {
                  return input.hasClass('ng-invalid');
              }, function(isInvalid) {
                  element.toggleClass('has-error', isInvalid);
              });
          }
      }
  };
}]);

然后简单地在模板中使用它

<div class="form-group" bs-has-error>
    <input class="form-control" ng-model="foo" ng-pattern="/.../"/>
</div>
于 2014-02-12T21:20:11.377 回答
22

@farincz 的回答略有改进。我同意指令是这里最好的方法,但我不想在每个.form-group元素上重复它,所以我更新了代码以允许将其添加.form-group到父元素或父<form>元素(这会将它添加到所有包含的.form-group元素):

angular.module('directives', [])
  .directive('showValidation', [function() {
    return {
        restrict: "A",
        link: function(scope, element, attrs, ctrl) {

            if (element.get(0).nodeName.toLowerCase() === 'form') {
                element.find('.form-group').each(function(i, formGroup) {
                    showValidation(angular.element(formGroup));
                });
            } else {
                showValidation(element);
            }

            function showValidation(formGroupEl) {
                var input = formGroupEl.find('input[ng-model],textarea[ng-model]');
                if (input.length > 0) {
                    scope.$watch(function() {
                        return input.hasClass('ng-invalid');
                    }, function(isInvalid) {
                        formGroupEl.toggleClass('has-error', isInvalid);
                    });
                }
            }
        }
    };
}]);
于 2014-03-19T12:30:53.723 回答
17

@Andrew Smith 的回答略有改进。我更改输入元素并使用require关键字。

.directive('showValidation', [function() {
    return {
        restrict: "A",
        require:'form',
        link: function(scope, element, attrs, formCtrl) {
            element.find('.form-group').each(function() {
                var $formGroup=$(this);
                var $inputs = $formGroup.find('input[ng-model],textarea[ng-model],select[ng-model]');

                if ($inputs.length > 0) {
                    $inputs.each(function() {
                        var $input=$(this);
                        scope.$watch(function() {
                            return $input.hasClass('ng-invalid');
                        }, function(isInvalid) {
                            $formGroup.toggleClass('has-error', isInvalid);
                        });
                    });
                }
            });
        }
    };
}]);
于 2014-07-04T08:54:25.393 回答
11

感谢@farincz 的精彩回答。以下是我为适应我的用例所做的一些修改。

这个版本提供了三个指令:

  • bs-has-success
  • bs-has-error
  • bs-has(当你想同时使用另外两个时很方便)

我所做的修改:

  • 添加了一个检查以仅在表单字段脏时显示状态,即在有人与它们交互之前它们不会显示。
  • element.find()为不使用 jQuery 的人 更改了传入的字符串,因为element.find()Angular 的 jQLite 仅支持通过标记名查找元素。
  • 添加了对选择框和文本区域的支持。
  • 包装element.find()在 a$timeout中以支持元素可能尚未将其子元素呈现给 DOM 的情况(例如,如果元素的子元素被标记为ng-if)。
  • 更改if表达式以检查返回数组的长度(if(input)来自 @farincz 的答案始终返回 true,因为返回 fromelement.find()是一个 jQuery 数组)。

我希望有人觉得这很有用!

angular.module('bs-has', [])
  .factory('bsProcessValidator', function($timeout) {
    return function(scope, element, ngClass, bsClass) {
      $timeout(function() {
        var input = element.find('input');
        if(!input.length) { input = element.find('select'); }
        if(!input.length) { input = element.find('textarea'); }
        if (input.length) {
            scope.$watch(function() {
                return input.hasClass(ngClass) && input.hasClass('ng-dirty');
            }, function(isValid) {
                element.toggleClass(bsClass, isValid);
            });
        }
      });
    };
  })
  .directive('bsHasSuccess', function(bsProcessValidator) {
    return {
      restrict: 'A',
      link: function(scope, element) {
        bsProcessValidator(scope, element, 'ng-valid', 'has-success');
      }
    };
  })
  .directive('bsHasError', function(bsProcessValidator) {
    return {
      restrict: 'A',
      link: function(scope, element) {
        bsProcessValidator(scope, element, 'ng-invalid', 'has-error');
      }
    };
  })
  .directive('bsHas', function(bsProcessValidator) {
    return {
      restrict: 'A',
      link: function(scope, element) {
        bsProcessValidator(scope, element, 'ng-valid', 'has-success');
        bsProcessValidator(scope, element, 'ng-invalid', 'has-error');
      }
    };
  });

用法:

<!-- Will show success and error states when form field is dirty -->
<div class="form-control" bs-has>
  <label for="text"></label>
  <input 
   type="text" 
   id="text" 
   name="text" 
   ng-model="data.text" 
   required>
</div>

<!-- Will show success state when select box is anything but the first (placeholder) option -->
<div class="form-control" bs-has-success>
  <label for="select"></label>
  <select 
   id="select" 
   name="select" 
   ng-model="data.select" 
   ng-options="option.name for option in data.selectOptions"
   required>
    <option value="">-- Make a Choice --</option>
  </select>
</div>

<!-- Will show error state when textarea is dirty and empty -->
<div class="form-control" bs-has-error>
  <label for="textarea"></label>
  <textarea 
   id="textarea" 
   name="textarea" 
   ng-model="data.textarea" 
   required></textarea>
</div>

您还可以安装 Guilherme 的bower 包,它将所有这些捆绑在一起。

于 2014-05-12T20:44:14.977 回答
4

如果样式是问题,但您不想禁用本机验证,为什么不使用您自己的更具体的样式覆盖样式?

input.ng-invalid, input.ng-invalid:invalid {
   background: red;
   /*override any styling giving you fits here*/
}

使用 CSS 选择器的特性级联你的问题!

于 2013-02-04T20:39:07.570 回答
2

我对 Jason Im 的回答的改进如下添加了两个新指令 show-validation-errors 和 show-validation-error。

'use strict';
(function() {

    function getParentFormName(element,$log) {
        var parentForm = element.parents('form:first');
        var parentFormName = parentForm.attr('name');

        if(!parentFormName){
            $log.error("Form name not specified!");
            return;
        }

        return parentFormName;
    }

    angular.module('directives').directive('showValidation', function () {
        return {
            restrict: 'A',
            require: 'form',
            link: function ($scope, element) {
                element.find('.form-group').each(function () {
                    var formGroup = $(this);
                    var inputs = formGroup.find('input[ng-model],textarea[ng-model],select[ng-model]');

                    if (inputs.length > 0) {
                        inputs.each(function () {
                            var input = $(this);
                            $scope.$watch(function () {
                                return input.hasClass('ng-invalid') && !input.hasClass('ng-pristine');
                            }, function (isInvalid) {
                                formGroup.toggleClass('has-error', isInvalid);
                            });
                            $scope.$watch(function () {
                                return input.hasClass('ng-valid') && !input.hasClass('ng-pristine');
                            }, function (isInvalid) {
                                formGroup.toggleClass('has-success', isInvalid);
                            });
                        });
                    }
                });
            }
        };
    });

    angular.module('directives').directive('showValidationErrors', function ($log) {
        return {
            restrict: 'A',
            link: function ($scope, element, attrs) {
                var parentFormName = getParentFormName(element,$log);
                var inputName = attrs['showValidationErrors'];
                element.addClass('ng-hide');

                if(!inputName){
                    $log.error("input name not specified!")
                    return;
                }

                $scope.$watch(function () {
                    return !($scope[parentFormName][inputName].$dirty && $scope[parentFormName][inputName].$invalid);
                },function(noErrors){
                    element.toggleClass('ng-hide',noErrors);
                });

            }
        };
    });

    angular.module('friport').directive('showValidationError', function ($log) {
        return {
            restrict: 'A',
            link: function ($scope, element, attrs) {
                var parentFormName = getParentFormName(element,$log);
                var parentContainer = element.parents('*[show-validation-errors]:first');
                var inputName = parentContainer.attr('show-validation-errors');
                var type = attrs['showValidationError'];

                element.addClass('ng-hide');

                if(!inputName){
                    $log.error("Could not find parent show-validation-errors!");
                    return;
                }

                if(!type){
                    $log.error("Could not find validation error type!");
                    return;
                }

                $scope.$watch(function () {
                    return !$scope[parentFormName][inputName].$error[type];
                },function(noErrors){
                    element.toggleClass('ng-hide',noErrors);
                });

            }
        };
    });

})();

可以将 show-validation-errors 添加到错误容器中,以便根据表单字段的有效性显示/隐藏容器。

并且 show-validation-error 根据给定类型的表单字段有效性显示或隐藏元素。

预期用途示例:

        <form role="form" name="organizationForm" novalidate show-validation>
            <div class="form-group">
                <label for="organizationNumber">Organization number</label>
                <input type="text" class="form-control" id="organizationNumber" name="organizationNumber" required ng-pattern="/^[0-9]{3}[ ]?[0-9]{3}[ ]?[0-9]{3}$/" ng-model="organizationNumber">
                <div class="help-block with-errors" show-validation-errors="organizationNumber">
                    <div show-validation-error="required">
                        Organization number is required.
                    </div>
                    <div show-validation-error="pattern">
                        Organization number needs to have the following format "000 000 000" or "000000000".
                    </div>
                </div>
            </div>
       </form>
于 2014-10-17T09:51:47.460 回答
2

我认为现在回复为时已晚,但希望你会喜欢它:

CSS,您可以添加其他类型的控件,例如选择、日期、密码等

input[type="text"].ng-invalid{
    border-left: 5px solid #ff0000;
    background-color: #FFEBD6;
}
input[type="text"].ng-valid{
    background-color: #FFFFFF;
    border-left: 5px solid #088b0b;
}
input[type="text"]:disabled.ng-valid{
    background-color: #efefef;
    border: 1px solid #bbb;
}

HTML:不需要在控件中添加任何东西,除非是 ng-required

<input type="text"
       class="form-control"
       ng-model="customer.ZipCode"
       ng-required="true">

只需尝试并在您的控件中键入一些文本,我发现它非常方便且很棒。

于 2015-07-19T21:29:37.800 回答
1

没有小提琴很难确定,但查看 angular.js 代码它不会替换类 - 它只是添加和删除自己的。因此,任何引导类(由引导 UI 脚本动态添加)都应该不受 Angular 的影响。

也就是说,与 Angular 同时使用 Bootstrap 的 JS 功能进行验证是没有意义的——只使用 Angular。我建议您使用引导样式和角度 JS,即使用自定义验证指令将引导 css 类添加到您的元素中。

于 2013-01-16T13:57:08.070 回答
1
<div class="form-group has-feedback" ng-class="{ 'has-error': form.uemail.$invalid && form.uemail.$dirty }">
  <label class="control-label col-sm-2" for="email">Email</label>
  <div class="col-sm-10">
    <input type="email" class="form-control" ng-model="user.email" name="uemail" placeholder="Enter email" required>
    <div ng-show="form.$submitted || form.uphone.$touched" ng-class="{ 'has-success': form.uemail.$valid && form.uemail.$dirty }">
    <span ng-show="form.uemail.$valid" class="glyphicon glyphicon-ok-sign form-control-feedback" aria-hidden="true"></span>
    <span ng-show="form.uemail.$invalid && form.uemail.$dirty" class="glyphicon glyphicon-remove-circle form-control-feedback" aria-hidden="true"></span>
    </div>
  </div>
</div>
于 2015-12-28T11:22:07.043 回答
1

当我没有听说过 AngularJS 本身的名字时,我知道这是一个非常古老的问题答案线程 :-)

但是对于那些登陆此页面以干净和自动化的方式寻找 Angular + Bootstrap 表单验证的其他人,我编写了一个非常小的模块来实现相同的目标,而无需以任何形式更改 HTML 或 Javascript。

结帐引导角度验证

以下是三个简单的步骤:

  1. 通过 Bower 安装bower install bootstrap-angular-validation --save
  2. 添加脚本文件<script src="bower_components/bootstrap-angular-validation/dist/bootstrap-angular-validation.min.js"></script>
  3. 将依赖项添加bootstrap.angular.validation到您的应用程序中,就是这样!

这适用于 Bootstrap 3,不需要jQuery

这是基于 jQuery 验证的概念。该模块为验证错误提供了一些额外的验证和常见的通用消息。

于 2016-06-03T17:12:19.630 回答