Angular2: Conditional required validation

angular 6 conditional validation reactive forms
angular 6 conditional required
angular 4 remove required validator conditionally
ng-required conditional
angular2 form validation
required with condition in angular 2
dynamically set required field validator
angular 2 conditional validation template driven form

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.


I had a similar problem but couldn't find a answer. Since nobody has answered this yet I'll provide an example of how I solved my problem, and how you can solve your issue using the same solution.

Example: (Phone number is required only if email is not set)

export class UserComponent implements OnInit {

userForm: FormGroup;

constructor(private fb: FormBuilder) {}

ngOnInit() {

    //Create my userForm and and add initial validators
    this.userForm = this.fb.group({
        username: [null, [Validators.required]],
        name: [null, [Validators.required]],
        email: [],
        phoneNumber: [null, [Validators.required, Validators.minLength(4)],
    });

    //Listen to email value and update validators of phoneNumber accordingly
    this.userForm.get('email').valueChanges.subscribe(data => this.onEmailValueChanged(data));
}


onEmailValueChanged(value: any){
    let phoneNumberControl = this.userForm.get('phoneNumber');

    // Using setValidators to add and remove validators. No better support for adding and removing validators to controller atm.
    // See issue: https://github.com/angular/angular/issues/10567
    if(!value){
        phoneNumberControl.setValidators([Validators.required, Validators.minLength(4)]);
    }else {
        phoneNumberControl.setValidators([Validators.minLength(4)]);
    }

    phoneNumberControl.updateValueAndValidity(); //Need to call this to trigger a update
}

}

So in your case you should add a changeListener to "_ansat" equal to my email listener, and then add required to "_helbred" accordingly.

3 ways to implement conditional validation of Angular reactive forms, I will call it dynamic or conditional validation. Sounds like a trivial task for Angular. Let's create an html structure and a typescript code needed. Now, let's implement our conditional validation function. As mentioned in Using Angular 2's Model-Driven Forms, each form control exposes the valueChanges event, which we can subscribe to. We will also subscribe to the payment method type value change event. Each time the payment method type changes, we will update our validation accordingly.


Just add validator for the field:

if(some_logic) {
 this.your_form.get('field_name').setValidators([Validators.required]);
}

How to Implement Conditional Validation in Angular 2 Model-driven , Angular 2 - Conditional Validation (final) scotch contains all the default validators (e.g. required, minlength, etc) that Angular provide us. This page will walk through Angular conditional validation tutorial. We perform conditional validation using valueChanges property or registerOnValidatorChange() method. We subscribe valueChanges of a form control to set and clear validators on any field in reactive form and we call updateValueAndValidity() to recalculate the value and validation status of the control.


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…]);
}

Angular Validators With Conditional Validation In Reactive Forms , This is all that is needed to start implementing the reactive form validations. Let's go back to our component class! Adding Validation. We will be  Angular 2: Conditional Validation with Reactive Forms. Forms are ubiquitous. Wherever a user has to enter multiple pieces of information to be submitted and processed, a form is generally how it’s done. Being such a widespread source of data input, validation of forms is crucial.


Conditional Required Validator in Angular 2, DOCTYPE html> <html> <head> <title>Conditional Required Validator <script src="https://code.angularjs.org/2.0.0-beta.16/angular2-polyfills.js"></script>  This works fine if the user first toggles the check box and then types or erases text in the text box. However, if the user toggles the check box while the text box is blank, then the validation message doesn't update appropriately. How can I modify MyRequiredValidator to trigger validation when its required property is changed?


Perform Conditional Validation With the valueChanges Method in , to enable conditional validation in Angular-based web applications then the Phone Number field should be required, otherwise, it should  Suppose we have a form to fill some personal family details: name, birth date, partner details, and children details. And we want the child name to be required, but only if the user has children


Angular 2: Conditional Validation with Reactive Forms, Angular 2: Conditional Validation with Reactive Forms required> </div> <div> <​label for=“zipcode">Zip Code</label> <input name="zipcode"  In this way you can use conditional required fill in AngularJs. but it does appear to do the conditional validation. Angular2+ isn't tagged on this question.