Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

445
Visualizações
Angular - Conditional Custom Validator on a FormGroup Inside of a FormGroup

I have a form that needs to check if one of a group of checkboxes is checked if a dropdown has a specific value. I have a validator that works on the checkboxes, but I only need it to check if the dropdown is a specific value. Below is the form and validation code. I've tried having the validator bind like this.requireCheckboxesValidator.bind(this), but then it just seems to ignore the validator

  readonly closeFormGroup: FormGroup;


  constructor(
    formBuilder: FormBuilder,
  ) {
    this.closeFormGroup = formBuilder.group({
      notes: [null],
      reason: [1, Validators.required],
      checkBoxGroup: new FormGroup({
        checkBox1: new FormControl(false),
        checkBox2: new FormControl(false),
        checkBox3: new FormControl(false),
        checkBox4: new FormControl(false),
        checkBox5: new FormControl(false),
      } ,this.requireCheckboxesValidator())
    });
  }
  public requireCheckboxesValidator(): ValidatorFn {
    return function validate(formGroup: FormGroup) {
      let checked = 0;
      console.log(formGroup);
      Object.keys(formGroup.controls).forEach(key => {
         const control = formGroup.controls[key];

         if (control.value === true) {
           checked++;
         }
       });

      if (checked < 1) {
        return {
          requireCheckboxesToBeChecked: true,
        };
      }

      return null;
    };
  }
about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

I can suggest a different approach.
You can subscribe to valueChanges of your dropdown field and then if the specific value that is selected is what you expect, you can use addValidator to add the certain validator to your checkboxes form control.
I also like your idea of adding a custom validator (definitely the better approach) and it should actually work in that way as well. From what I understand you're trying to add the validator for the checkboxes only if the dropdown has a specific value ? In that case you need to change your logic to something like:

      Object.keys(formGroup.controls).forEach(key => {
         const control = formGroup.controls[key];

         if (control.value === true) {
           checked++;
         }
        let dropdownValue = undefined;
        if (key === 'dropdownFormControlKey') {
            dropdownValue = control.value;
        }
       });

      if (checked < 1) { // --- Add check to also see if the dropdown's value is what you expect and only then return the error
        return {
          requireCheckboxesToBeChecked: true,
        };
      }

      return null;
    };
  • Also, I would suggest not to define the validator function in your component, instead follow this article to see a proper approach - https://angular.io/guide/form-validation
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda