I'm trying to add custom validator to my component.ts
customvalidatorFile:
import { FormGroup, ValidationErrors } from '@angular/forms';
export class ProfileCustomValidators {
static validateTime(fg: FormGroup): ValidationErrors {
const staffForm = fg.get('staffForm')
const fromTime = staffForm.get('fromTime').value;
const toTime = staffForm.get('toTime').value;
if(fromTime > toTime) {
return {
'endTime': {
message: 'End time should be greater than start time'
}
}
}
return null;
}
}
component.ts
export class StaffFrom implements onInit {
staffForm: FormGroup;
constructor(private fb: FormBuilder){}
ngOnInit() {
this.staffForm = this.fb.group({
fromTime: new FormControl(null, Validators.required),
toTime: new FormControl(null, Validators.required),
}{ validator: ProfileCustomValidators.validateTime})
}
Component.html
<div>
<form [formGroup]="staffForm">
<mat-form-field>
<input
type="time"
required
formControlName="fromTime"
matInput
placeholder="From"
/>
</mat-form-field>
<mat-form-field>
<input
type="time"
required
formControlName="toTime"
matInput
placeholder="To"
/>
</mat-form-field>
</form>
</div>
By using the above code I get the following error
Cannot read property 'get' of null
I need some help in fixing this and also how to access staffForm in custom.validator file since it is returning null. Thank you.