I am currently implementing validation for my form. The discount
field must not be empty and its value should range from 0 to 100, while the time_from
and time_to
fields cannot be left empty. However, I am facing an issue with firing the validation process specifically on the time_from
and time_to
fields. I am using the PrimeNG Calendar component and discovered that the p-calendar
validation works well with ngModule
, but I have been unable to find a solution for form groups.
Component (simplified)
ngOnInit() {
this.buildForm();
}
buildForm(): void {
this.discountFG = this.fb.group({
discount: new FormControl('', [Validators.required, CustomValidators.range([0, 100])]),
time_from: new FormControl('', Validators.required),
time_to: new FormControl('', Validators.required)
});
this.discountFG.valueChanges
.subscribe(data => this.onValueChanged(data));
}
onValueChanged(data?: any) {
if (!this.discountFG) { return; }
const form = this.discountFG;
for (const field in this.formErrors) {
// clear previous error message (if any)
this.formErrors[field] = '';
const control = form.get(field);
if (control && control.dirty && !control.valid) {
const messages = this.validationMessages[field];
for (const key in control.errors) {
this.formErrors[field] += messages[key] + ' ';
}
}
}
}
Template (simplified)
<p-calendar formControlname="time_from" [locale]="pl" dateFormat="yy-mm-dd" [monthNavigator]="true" [yearNavigator]="true"
yearRange="2010:2030" (blur)="setTimeFrom($event)" readonlyInput="true" required></p-calendar>
<p-calendar formControlname="time_to" [locale]="pl" dateFormat="yy-mm-dd" [monthNavigator]="true" [yearNavigator]="true"
yearRange="2010:2030" [minDate]="minDate" readonlyInput="true" required></p-calendar>
Current behavior
The validators do not recognize when a date is selected, leading to no event being triggered to capture the value change. As a result, the onValueChanged
function incorrectly assumes that time_from
and time_to
have not been interacted with.
How can I resolve this issue ?