如何聚合多个字段的ngMessage

How to aggregate ngMessage of several field

我正在使用 Angular JS ngMessage 指令进行表单验证,我想聚合几个字段的 ngMessage 警报。基本上,我的表单包含 3 个输入(日、月、年),我想在日期无效时显示警报(无论是无效的日期、月份或年份)。我怎样才能做到这一点?我有 plunkered 我的问题,这里是我如何使用 ngMessage 指令:

<form name="messageAnimationForm">
  <label for="day">Day</label>
  <input ng-model="day" id="day" name="day" ng-minlength="1" ng-maxlength="2" required class="ngMessageSample" ng-pattern="/^\d+$/"/> <br/><br/>
  <label for="month">Month</label>
  <input ng-model="month" id="month" name="month" ng-minlength="1" ng-maxlength="2" required class="ngMessageSample" ng-pattern="/^\d+$/"/><br/><br/>
  <label for="year">Year</label>
  <input ng-model="year" id="year" name="year" ng-minlength="4" ng-maxlength="4" required class="ngMessageSample" ng-pattern="/^\d+$/"/><br/><br/>

  <div>
    <div ng-messages="messageAnimationForm.day.$error" class="ngMessagesClass" ng-messages-multiple>
      <div ng-message="pattern" class="ngMessageClass">* This field is invalid, only numbers are allowed</div>
      <div ng-message="required" class="ngMessageClass">* Day is mandatory</div>
    </div>

    <div ng-messages="messageAnimationForm.month.$error" class="ngMessagesClass" ng-messages-multiple>
      <div ng-message="pattern" class="ngMessageClass">* This field is invalid, only numbers are allowed</div>
      <div ng-message="required" class="ngMessageClass">* Month is mandatory</div>
    </div>

    <div ng-messages="messageAnimationForm.year.$error" class="ngMessagesClass" ng-messages-multiple>
      <div ng-message="pattern" class="ngMessageClass">* This field is invalid, only numbers are allowed</div>
      <div ng-message="required" class="ngMessageClass">* Year is mandatory</div>
    </div>
  </div>
</form>

您可以通过 messageAnimationForm.$error:

检查您的整个表单是否有误
<div ng-messages="messageAnimationForm.$error" class="ngMessagesClass" ng-messages-multiple>
  <div ng-message="pattern" class="ngMessageClass">* A field is invalid, only numbers are allowed</div>
  <div ng-message="minlength" class="ngMessageClass">* It's mandatory at least 1 characters</div>
  <div ng-message="maxlength" class="ngMessageClass">* It's mandatory at most 2 characters</div>
</div>

Forked your Plunker here.

尝试将自定义验证器添加到三个字段之一并从您的控制器手动触发它(或将监视添加到三个日期组件以触发您的验证功能):

<form name="messageAnimationForm">
<div ng-messages="messageAnimationForm.year.$error" class="ngMessagesClass" ng-messages-multiple>
  <div ng-message="invalidDate" class="ngMessageClass">Date not valid</div>
</div>
</form>

然后,在您的控制器中,您必须使用您的自定义规则检查日期的有效性。如果您希望显示消息,则必须将自定义错误设置为 true(或设置为 "false" 以隐藏它):

$scope.messageAnimationForm.year.$error.invalidDate = checkIfYourDateIsValid();