I am working on form in angular And there is an optional field which has from and to time and I have to make condition that I only enter the from time or to time and not both times then I should see the error message but its an optional field so I have to make a custom validator for this one and I am confused about how to make this custom validation functionality for an optional field. so if anyone can help it will be great.
this is my html form code:
<div class="form-group">
<div class="col-lg-12 d-inline-flex">
<span id="working-hours-text" class=" text-nowrap span-width" for="workingHoursFrom" [ngClass]="{'error-line-spacing': ((workHoursFrom.dirty && workHoursFrom.touched) && !workHoursTo.dirty) || (!workHoursFrom.dirty && (workHoursTo.dirty && workHoursTo.touched))}"> Working Hours:</span>
<div class="w-100">
<div id="working-hours-errorMsg" *ngIf="((workHoursFrom.dirty && workHoursFrom.touched) && !workHoursTo.dirty) || (!workHoursFrom.dirty && (workHoursTo.dirty && workHoursTo.touched))" class="help-block text-danger w-100 text-center pr-5 body-text-1">Please enter both the From and To working hours</div>
<div class="d-inline-flex w-100">
<div class=" w-100 d-inline-flex form-control text-center m-auto" [ngClass]="{'red-border': ((workHoursFrom.dirty && workHoursFrom.touched) && !workHoursTo.dirty) || (!workHoursFrom.dirty && (workHoursTo.dirty && workHoursTo.touched))}">
<input id="input-working-from" formControlName="workingHoursFrom" type="time" class=" text-center m-auto pr-2 col-6" style="border: none;">
<span>-</span>
<input id="input-working-to" formControlName="workingHoursTo" type="time" class=" text-center m-auto pl-2 col-6" style="border: none;">
</div>
<em id="working-hours-errorMsg-icon" *ngIf="((workHoursFrom.dirty && workHoursFrom.touched) && !workHoursTo.dirty) || (!workHoursFrom.dirty && (workHoursTo.dirty && workHoursTo.touched))"
style="padding-left: 15px;" class="fas fa-exclamation-circle red-symbol"></em>
</div>
</div>
</div>
</div>
this is my ts file:
this.form = new FormGroup({
workingHoursFrom: new FormControl('', [Validators.pattern('^(2[0-4]|[0-1][0-9]):[0-5][0-9]$')]),
workingHoursTo: new FormControl('', [Validators.pattern('^(2[0-4]|[0-1][0-9]):[0-5][0-9]$')])
});
get workHoursFrom(){ return this.form.get('workingHoursFrom');}
get workHoursTo(){return this.form.get('workingHoursTo');}