Home > Back-end >  How can I validate my control on condition using abstract validators?
How can I validate my control on condition using abstract validators?

Time:07-02

one of my controls is a bool and if that control is true i want the two of my another controls to be required else they can be null.

const controls = [
            {name: "bool", control: new FormControl(''), validators: []},
            {name: "firstName", control: new FormControl(''), validators: ???},
            {name: "lastName", control: new FormControl(''), validators: ???},

CodePudding user response:

You want to cross validate: https://angular.io/guide/form-validation#adding-cross-validation-to-reactive-forms

Or use regex like:

controls.get('bool').value === true ? Validators.required : null 

Or set them programmatically

if (controls.get('bool').value === true) {
controls['firstName'].setValidators([Validators.required])
}

CodePudding user response:

Or you can do something like the following

controls.get('bool').valueChanges.subscribe((value)=>{
    if(value){
    controls.get('firstName).setValidators([Validators.required])
    controls.get('lastName).setValidators([Validators.required])
    return
    }
    controls.get('firstName).removeValidators([Validators.required])
    controls.get('lastName).removeValidators([Validators.required])
 
})

now when value of bool is changing the validators will be set accordingly

  • Related