I am trying to create a conditional required validation on a specific field.I try doing this by return Validators.required back in my function, but this doesn't seem to work. How do I go about doing this? Here's my code:
private _ansat: AbstractControl = new FormControl('', Validators.required);
private _helbred: AbstractControl = new FormControl('', Validators.compose([this.useValidateIfRadio(this._ansat, 0, Validators.required)]) );
constructor(private _fb: FormBuilder) {
this.myForm = this._fb.group({
ansat: this._ansat,
helbred: this._helbred
});
}
useValidateIfRadio (c: AbstractControl, n: number, v) {
return function (control) {
return new Promise(resolve => {
// this.msg = ansatControl.value;
console.log(v);
if (c.value === n) {
resolve(v);
}
else {
resolve(null);
}
});
};
};
Any help is greatly appreciated.
Another way to achieve conditional validation in Angular forms would be to write your own group validator. This validator will check the value of the whole group, including the a checkbox. If the checkbox is set, it will require the myEmailField not to be empty.
In a reactive form, the source of truth is the component class. Instead of adding validators through attributes in the template, you add validator functions directly to the form control model in the component class. Angular then calls these functions whenever the value of the control changes.
You can subscribe to value changes of a control or the whole form. updateValueAndValidity allows you to modify the value of one or more form controls and the flag allows you to specify if you want this to emit the value to valueChanges subscribers.
These answers got me most of the way there, but I found out a pretty big gotcha… in some cases, setValidators only adds to the existing array of validators and does not work well to clear them. In some cases, like when ngOnInit loads twice in a row, the conditions could be first negative and then positive for a passed-in value you're depending on. In such a case, you will set it to required, then later attempt to clear it, but the UI will still behave like it expects it. To fix this, consider the following...
const myControl = this.your_form.get('field_name');
if(some_logic) {
myControl.clearAsyncValidators();
myControl.clearValidators();
myControl.updateValueAndValidity({onlySelf:true});
} else {
myControl.setValidators([Validators.required, Validators.other…]);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With