marquee
marquee

Reputation: 33

How do I make a validator for a checkbox using a formBuilder Array in angular 9?

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;

Upvotes: 1

Views: 715

Answers (2)

Priscila Anjos
Priscila Anjos

Reputation: 106

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.

Upvotes: 2

Brian Smith
Brian Smith

Reputation: 1656

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.

Upvotes: 2

Related Questions