I have an Angular 9 form where four fields are related. One is a checkbox, and the rest are inputs. When the checkbox is checked, the inputs should not be empty, but when it is not checked, it doesn't matter. I want to make validators for this, so that errors appear only when a field is empty and the first field is set to true.
I have also considered creating a local boolean representing the state of the checkmark, and passing this to the validator like so.
export function linkedFieldValidator(toggler: boolean): ValidatorFn {
console.log('updated');
return (control: AbstractControl): {[key: string]: any} | null => {
return (toggler && control.value === '') ? {linkedField: {value: control.value}} : null;
};
}
...
field: new FormControl('', linkedFieldValidator(this.checkboxvalue)),
...
This doesn't work, however, I imagine since it only passes the value of the boolean once and doesn't update after. Even calling updateValueAndValidity()
doesn't work, which is odd to me (if this is not it, then what is its purpose?).
The structure of my FormGroup
looks something like this:
this.form = this.formBuilder.group({
name: new FormControl(''), // don't care
address: new FormControl(''), // don't care
car: new FormControl(false), // do care - this is the checkmark
license_plate: new FormControl('', Validators.pattern(MY_LICENSE_PLATE_REGEX)), // shouldn't be empty when car
mileage: new FormControl('') // shouldn't be empty when car
hair: new FormControl(false), // do care - this is the checkmark
hair_color: new FormControl(''), // shouldn't be empty when hair
});
As you can see, I have a couple of FormControll
s through each other and I only want a couple of them to be linked. Another important thing to note is that, while the whole form can be made invalid if one of these conditions is violated, I want to be able to address each error individually so that I can display proper messages in the proper places.
I have no more ideas, can anyone help me? I am using reactive forms.