1

I need to validate that my user selects at least one viewport. I simply added the validator.required for the input but for the checkbox in an array I am not sure how to validate it.

public createForm(): FormGroup {
    return this.formBuilder.group({
        urlInput: ['', [ Validators.required, Validators.pattern(URL_VALIDATOR) ]],
        children: [false, []],
        viewport: this.formBuilder.array(this.viewports.map(x => false))
    });
}

I used this to create the checkbox:

 public ngOnInit(): void {
    this.urlForm = this.createForm();
    const checkboxControl = this.urlForm.controls.viewport as FormArray;
3
  • I realized I can simply add the Validator.required as well into the viewport however it is requiring every single item to be check before in becomes valid. viewport: this.formBuilder.array(this.viewports.map(x => [false, [Validators.required]])) Commented Jun 25, 2021 at 23:02
  • 1
    To verify, you will have a list of checkboxes and you require that at least 1 is checked? Commented Jun 25, 2021 at 23:17
  • yes that is correct Commented Jun 25, 2021 at 23:28

2 Answers 2

2

You could create a custom validator for your form:

Validator:

export function minimumNeededSelected(
  controlArrayName: string,
  quantityNeededSelected: number
) {
  return (formGroup: FormGroup) => {
    const controlArray = formGroup.controls[controlArrayName];

    let quantitySelected = 0;
    (controlArray as FormArray).controls.forEach(control => {
      if (control.value) {
        quantitySelected++;
      }
    });

    if (quantitySelected < quantityNeededSelected) {
      controlArray.setErrors({ minimumNeededSelected: true });
    } else {
      controlArray.setErrors(null);
    }
  };
}

How to use:

public createForm(): FormGroup {
    return this.formBuilder.group({
        urlInput: ['', [ Validators.required, Validators.pattern(URL_VALIDATOR) ]],
        children: [false, []],
        viewport: this.formBuilder.array(this.viewports.map(x => false))
    },
    {
      validators: [minimumNeededSelected('viewport', 1)]
    });
}

This way your formArray will get an error of 'minimumNeededSelected' if there is not enough items selected.

Sign up to request clarification or add additional context in comments.

Comments

2

You can create a function that returns if a viewport is checked or not.

hasCheckedItem(): boolean {
    const viewports = this.urlForm.get('viewport') as FormArray;
    if (viewports) {
      viewports.controls.forEach(control => {
        if (control.value) {
          return true;
        }
      });
    }
    return false;
  } 

You can then perform this check before a form submit or next action taken where this needs to be true.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.