Requiring a checkbox to be checked

nathasm picture nathasm · Feb 17, 2016 · Viewed 68.5k times · Source

I want a button to be disabled until a checkbox has been checked using a FormBuilder for Angular. I don't want to explicitly check the value of the checkbox and would prefer to use a validator so that I can simply check form.valid.

In both validation cases below the checkbox is

interface ValidationResult {
  [key:string]:boolean;
}

export class CheckboxValidator {
  static checked(control:Control) {
    return { "checked": control.value };
  }
}

@Component({
  selector: 'my-form',
  directives: [FORM_DIRECTIVES],
  template: `  <form [ngFormModel]="form" (ngSubmit)="onSubmit(form.value)">
    <input type="checkbox" id="cb" ngControl="cb">
    <button type="submit" [disabled]="!form.valid">
    </form>`
})

export class SomeForm {
  regForm: ControlGroup;

  constructor(fb: FormBuilder) {
    this.form = fb.group({
      cb: [ CheckboxValidator.checked ]
      //cb: [ false, Validators.required ] <-- I have also tried this
    });
  }

  onSubmit(value: any) {
    console.log('Submitted: ', this.form);
  }
}

Answer

developer033 picture developer033 · Jul 7, 2017

Since Angular 2.3.1 you can use Validators#requiredTrue:

Component:

this.formGroup = this.formBuilder.group({
  cb: [false, Validators.requiredTrue]
});

Template:

<form [formGroup]="formGroup">
  <label><input type="checkbox" formControlName="cb"> Accept it</label>
  <div style="color: red; padding-top: 0.2rem" *ngIf="formGroup.hasError('required', 'cb')">
    Required
  </div>
  <hr>
  <div>
    <button type="submit" [disabled]="formGroup.invalid">Submit</button>
  </div>
</form>

STACKBLITZ DEMO