Augustine
Augustine

Reputation: 109

Angular Validate field

I need to validate the two fields such that the minimum value should be less than the maximum value. As the user types a value in the minimum score and if it is greater than the maximum score, error must be thrown.

<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>

Upvotes: 0

Views: 64

Answers (2)

polyglot
polyglot

Reputation: 862

You should define a custom validator for this template-driven form so that the form itself fails to be submitted. Please look this blog to instruct how to make the custom validator. You can handle it better with reactive form instead of the template-driven one.

Upvotes: 1

Adil Khalil
Adil Khalil

Reputation: 2121

You can do something like

<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>

Upvotes: 1

Related Questions