I'm trying to add validation to my form.
discount
field cannot be empty and value range needs to be within 0 to 100, time_from
and time_to
cannot be empty. I cannot fire validation proccess on time_from
and time_to
. I use PrimeNG Calendar component. I found out that p-calendar
validation works great with ngModule
, but I couldnt find any 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
Validators dont notice if date is picked and because of this, no event is fired to catch value change, which means onValueChanged
thinks time_from
and time_to
is untouched.
How can I fix this ?
After some extensive debugging, I found out the form wasn't validating because of a syntax error :(, you spelled formControlName
with lowercase n
. At least, that's the case for the code you posted. Because of that, form controls were never getting the values.
I fixed it in Plunk and tried, it started working.
html:
<form (ngSubmit)="onSubmit()" [formGroup]="discountFG" class="box-model form-support-margin">
<p-calendar formControlName="time_from" dateFormat="yy-mm-dd" [monthNavigator]="true" [yearNavigator]="true"
yearRange="2010:2030" (blur)="setTimeFrom($event)" readonlyInput="true">
</p-calendar>
<p-calendar formControlName="time_to" dateFormat="yy-mm-dd" [monthNavigator]="true" [yearNavigator]="true"
yearRange="2010:2030" [minDate]="minDate" readonlyInput="true"></p-calendar>
<p></p>
<button md-raised-button color="primary" type="submit" [disabled]="!discountFG.valid">Save</button>
</form>