i'm creating a form with FormBuilder and i want to add a Validator to a formGroup.
Here is my code:
this.myForm = fb.group({
'name': ['', [Validators.maxLength(50), Validators.required]],
'surname': ['', [Validators.maxLength(50), Validators.required]],
'address': fb.group({
'street': ['', Validators.maxLength(300)],
'place': [''],
'postalcode': ['']
}),
'phone': ['', [Validators.maxLength(25), phoneValidator]],
'email': ['', emailValidator]
});
I would like to conditionally add validators to some of the address's formControls on certain conditions.
So I added a validator in the following way:
'address': fb.group({
'street': ['', Validators.maxLength(300)],
'place': [''],
'postalcode': ['']
}), { validator: fullAddressValidator })
Then i started to create a validator for the address FormGroup:
export const fullAddressValidator = (control:FormGroup) => {
var street:FormControl = control.controls.street;
var place:FormControl = control.controls.place;
var postalcode:FormControl = control.controls.postalcode;
if (my conditions are ok) {
return null;
} else {
return { valid: false };
}
};
I need to add the following conditions:
- If all fields are empty the form is valid
- If one of the field are filled in then all the fields must be required
- If
placeis instance of country (instead of city) thepostalcodeis optional - If the
postalcodeis filled in then thezipValidatormust be
added to its formControl
So, it is possible to add Angular2 Validators to a FormGroup on certain conditions?
If it does, how to implement my conditions? Can i use setValidators() and updateValueAndValidity() in the source code of another validator?