角度验证字段

时间:2020-07-23 10:00:47

标签: angular typescript

我需要验证两个字段,使得最小值应小于最大值。当用户在最小分数中输入一个值时,如果该值大于最大分数,则必须抛出错误。

<label class="col-2 col-form-label text-right font-weight-bold">Maximum Score*</label>
<div class="col-2">
  <input #firstScore="ngModel" [(ngModel)]="exams.firstScore" (keypress)="numberOnly($event)" name="firstScore" type="text">
</div>
<label class="col-3 col-form-label text-right font-weight-bold">Minimum Score*</label>
<div class="col-2">
  <input #secondScore="ngModel" [(ngModel)]="exams.secondScore" class="form-control" (keypress)="numberOnly($event)" name="secondScore" type="text"></div>
</div>

2 个答案:

答案 0 :(得分:1)

您可以做类似的事情

<label class="col-2 col-form-label text-right font-weight-bold">Maximum Score *</label>
<div class="col-2">
  <input #firstScore="ngModel" [(ngModel)]="exams.firstScore" (keypress)="numberOnly($event)" name="firstScore" type="text">
</div>
<label class="col-3 col-form-label text-right font-weight-bold">Manimum Score  *</label>
<div class="col-2">
  <input #secondScore="ngModel" [(ngModel)]="exams.secondScore" class="form-control" (keypress)="numberOnly($event)" name="secondScore" type="text"></div>
</div>
<span *ngIf="exams.secondScore > exams.firstScore">Your error message</span>

答案 1 :(得分:1)

您应该为此模板驱动的表单定义一个自定义验证器,以使表单本身无法提交。请查看此blog,以说明如何制作自定义验证器。您可以使用反应形式而不是模板驱动形式来更好地处理它。