我在 angularjs 中有表单,我正在验证电子邮件字段。 验证效果很好,但是当我添加另一个电子邮件字段时,验证适用于所有项目。但我只希望第一个字段按要求进行验证。
<form novalidate name="myForm">
<button class="btn btn-info btn-sm" ng-click="addNewChoice('email')">
<i class="fa fa-at"></i> Add Email
</button>
<br>
<div class="form-group row">
<div data-ng-repeat="email in emails">
<div class="col-md-4 col-sm-12" ng-class="{
'has-error' :isInputInvalid(myForm.email1),
'has-success' : isInputValid(myForm.email1)
}">
<label for="email{{ $index + 1}}">Email {{ $index + 1}}</label>
<input type="email" class="form-control" name="email{{ $index + 1}}" ng-model="formModel.emails[$index + 1]" id="email{{ $index + 1}}" placeholder="Enter email" required>
<span class="help-block" ng-show="myForm.email1.$error.required && myForm.email1.$dirty">Required</span>
<span class="help-block" ng-show="myForm.email1.$error.email">Email not valid!</span>
</div>
</div>
</div>
</form>
最佳答案
为了仅对 ng-repeat
呈现的列表中的第一项执行某些操作,您可以简单地使用 $first
。
因此,我们可以像这样使用ng-required
,而不是仅仅使用required
:
ng-required="{{$first}}"
而且,在所有使用的东西上使用 $first
,我们可以摆脱对除first之外的电子邮件的验证!
编辑:我从问题中了解到,除了首先之外,您不需要验证电子邮件。如果您担心即使第一个无效,第二个也无效,请检查 this fiddle它对输入的所有电子邮件进行单独验证。
关于javascript - 如何在使用 ng-repeat 时验证 AngularJs 中的表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42898538/