Reputation: 461
I must be missing something:
<input
formControlName="endDate"
type="date"
id="endDate"
class="form-control"
(change)="onDateChange()"
required
/>
<div *ngIf = "timesheetForm.get('endDate').errors?.invalidEndDate">
<small class="text-danger"> TTTT</small></div>
And the .ts
this.timesheetForm = this.fb.group({
endDate: ["", DateValidators.invalidEndDate],
}, {
validator: DateValidators.invalidEndDate
});
const endDateControl = this.timesheetForm.get('endDate');
endDateControl.valueChanges.subscribe((value) => {
if (value) {
this.timesheetForm.get('endDate').setValidators([DateValidators.invalidEndDate]);
} else {
this.timesheetForm.get('endDate').clearValidators();
}
});
And here's my custom validator
export class DateValidators {
static invalidEndDate(formGroup: FormGroup): ValidationErrors | null {
let startDateTimestamp: number;
let endDateTimestamp: number;
for (const controlName in formGroup.controls) {
if (controlName.indexOf("startDate") !== -1) {
startDateTimestamp = Date.parse(formGroup.controls[controlName].value);
}
if (controlName.indexOf("endDate") !== -1) {
endDateTimestamp = Date.parse(formGroup.controls[controlName].value);
}
}
return (endDateTimestamp < startDateTimestamp) ? { invalidEndDate : true} : null;
}
It's returning invalidEndDate:true, so the validation is working as expected but I am unable to display error message properly.
Upvotes: 0
Views: 210
Reputation: 7831
ValidatorFn INTERFACE
A function that receives a control and synchronously returns a map of validation errors if present, otherwise null.
based on angular.io docs:
interface ValidatorFn {
(control: AbstractControl): ValidationErrors | null
}
You must use control not formGroup in validator constructor.
Upvotes: 2