我正在使用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.
关于javascript - 如何聚合几个字段的ngMessage,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40846704/