Requiring a checkbox to be checked

AngularAngular2 FormsAngular Reactive-Forms

Angular Problem Overview


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);
  }
}

Angular Solutions


Solution 1 - Angular

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

Solution 2 - Angular

You could just use a ValidatorPattern and check for the right (boolean) value:

<input type="checkbox" [formControl]="myForm.controls['isTosRead']">

and here is the binding:

this.myForm = builder.group({
        isTosRead: [false, Validators.pattern('true')]
    });

Solution 3 - Angular

<h1>LOGIN</h1>
<form [formGroup]="signUpForm"> 
    <input type="checkbox" formControlName="cb">
    <button type="submit" [disabled]="!loginForm.valid" (click)="doLogin()">Log in</button>
</form>

export class Login { 
  public signUpForm: FormGroup;

  constructor(fb: FormBuilder) {
    this.signUpForm = fb.group({
      cb: [false, Validators.requiredTrue]
    });
  }
  doLogin() {

  }
}

Solution 4 - Angular

I found that Validator.required does not work properly for checkboxes. If you check a checkbox and then uncheck it, the FormControl will still show it as valid, even though it is unchecked. I think it only checks that you set it to something, be it true or false.

Here is a quick simple validator you can add to your FormControl:

  mustBeChecked(control: FormControl): {[key: string]: string} {
    if (!control.value) {
      return {mustBeCheckedError: 'Must be checked'};
    } else {
      return null;
    }
  }

Solution 5 - Angular

.ts

@Component({
  selector: 'my-app', 
  template: `
    <h1>LOGIN</h1>
    <form [ngFormModel]="loginForm"  #fm="ngForm"  (submit)="doLogin($event)"> 
  
          <input type="checkbox" id="cb" ngControl="cb" #cb="ngForm" required>
          <button type="submit" [disabled]="!loginForm.valid">Log in</button>
 
          <br/>
              <div>Valid ={{cb.valid}}</div>
              <div>Pristine ={{cb.pristine}}</div>
              <div>Touch ={{cb.touched}}</div>
              <div>form.valid?={{loginForm.valid}}</div>
          <BR/>
          <BR/>

    </form>
    `,
  directives: [ROUTER_DIRECTIVES,FORM_DIRECTIVES,CORE_DIRECTIVES]
})

export class Login { 
  constructor(fb: FormBuilder) {
    this.loginForm = fb.group({
      cb: [false, Validators.required],
    //cb: ['',Validators.required] - this will also work.
    
    });
  }
  doLogin(event) {
    console.log(this.loginForm);
    event.preventDefault();
  }
}

Working Plunker.

Please let me know if any changes required.

Solution 6 - Angular

I have this really simple example:

In your component:

login : FormGroup;

constructor(@Inject(FormBuilder)formBuilder : FormBuilder) {
this.login = formBuilder.group({userName: [null], password: [null],
staySignedIn: [false,Validators.pattern('true')]});
}

In your HTML:

<form [formGroup]="login" (ngSubmit)="onSubmit()">
    <div class="form-group">
        <input formControlName="userName" required>
    </div>
    <div class="form-group">
        <input formControlName="password" type="password" required>
    </div>
    <div>
        <label>
    <input formControlName="staySignedIn" checked="staySignedIn" type="checkbox"> bla
  </label>
    </div>
    <button type="submit">bla</button>
    <div >
        <a href>bla?</a>
    </div>
</form>

Solution 7 - Angular

For Angular 8, I did it like the below for checking if atleast one checkbox is checked amongst three checkboxes

form = new FormGroup({
    // ...more form controls...
    myCheckboxGroup: new FormGroup({
      myCheckbox1: new FormControl(false),
      myCheckbox2: new FormControl(false),
      myCheckbox3: new FormControl(false),
    }, requireCheckboxesToBeCheckedValidator()),
    // ...more form controls...
  });

created a custom validator

import { FormGroup, ValidatorFn } from '@angular/forms';

export function requireCheckboxesToBeCheckedValidator(minRequired = 1): ValidatorFn {
  return function validate (formGroup: FormGroup) {
    let checked = 0;

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

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

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

    return null;
  };
}

and used it like below in html

<ng-container [formGroup]="form">
   <!-- ...more form controls... -->

   <div class="form-group" formGroupName="myCheckboxGroup">
      <div class="custom-control custom-checkbox">
        <input type="checkbox" class="custom-control-input" formControlName="myCheckbox1" id="myCheckbox1">
        <label class="custom-control-label" for="myCheckbox1">Check</label>
      </div>

      <div class="custom-control custom-checkbox">
        <input type="checkbox" class="custom-control-input" formControlName="myCheckbox2" id="myCheckbox2">
        <label class="custom-control-label" for="myCheckbox2">At least</label>
      </div>

      <div class="custom-control custom-checkbox">
        <input type="checkbox" class="custom-control-input" formControlName="myCheckbox3" id="myCheckbox3">
        <label class="custom-control-label" for="myCheckbox3">One</label>
      </div>

      <div class="invalid-feedback" *ngIf="form.controls['myCheckboxGroup'].errors && form.controls['myCheckboxGroup'].errors.requireCheckboxesToBeChecked">At least one checkbox is required to check</div>
    </div>

    <!-- ...more form controls... -->
  </ng-container>

Solution 8 - Angular

If you are using PrimeNG, you can do it thru a TAG app-form-required-field, like this:

<p-checkbox name="_yes" #active="ngModel" required value="true" 
label="Active" binary="true" [(ngModel)]="filter._yes"></p-checkbox>

<p-checkbox name="_no" #inactive="ngModel" required label="Inactive" 
binary="true" [(ngModel)]="filter._no"></p-checkbox>

<app-form-required-field
     *ngIf="!filter._yes && !filter._no"
     [form]="active"
     [form]="inactive"
     id="msgAtivo"
     requiredMessage="Field required!"
>
</app-form-required-field>

Solution 9 - Angular

HTML Form

<div class="col-md-12">
                  <div class="form-group">
                      <input type="checkbox" class="form-check-input" id="agree" formControlName="agree">
                      <label class="form-check-label" for="agree">
                        I agree to our <a target="_blank" href="#">Terms of use</a> and
                        <a target="_blank" href="#">Privacy Policy</a>.
                      </label>
                      <div class="text-danger" *ngIf="(isRegSubmit||regForm.get('agree').touched) &&
                          regForm.get('agree').hasError('required')">
                          Please agree to terms of use and privacy policy.
                      </div>
                  </div>
              </div>

TS File

  regForm: FormGroup;isRegSubmit: boolean = false;
  constructor(
    private fb: FormBuilder
  }

  this.regForm = this.fb.group({
        agree    : [false, Validators.requiredTrue]
    });

Validators.required not worked Also, we can show error message by checking the value too and restrict the user to submit but it is not a good approach as we're not using validation, so whenever there is only a single checkbox then add Validators.requiredTrue instead of Validators.required

Solution 10 - Angular

despite of putting validator simple check below conditions

@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 && !cb.value">
    </form>`
})

Solution 11 - Angular

Coponent:

import { FormGroup, FormBuilder, Validators, AbstractControl } from '@angular/forms';

public profileForm!: FormGroup;

constructor(
    private _fb: FormBuilder
  ) { }
  
ngOnInit(): void {
    this._createForm();
    this._setValidationRule();
}

get fc(): { [key: string]: AbstractControl } {
    return this.profileForm.controls;
  }

  private _createForm() {
    const self = this;
    self.profileForm = self._fb.group({
      required_checkbox: [false],
      zipcode: [''],
      city: [''],
      town: [''],
    });
  }
  
  private _setValidationRule() {
    const self = this;
    self.profileForm.get('required_checkbox').valueChanges.subscribe(
      ruleStatus => {
        if (ruleStatus) {
          self.profileForm.get('zipcode').setValidators(Validators.required);
          self.profileForm.get('city').setValidators(Validators.required);
          self.profileForm.get('town').setValidators(Validators.required);
        } else {
          self.profileForm.get('zipcode').setValidators(null);
          self.profileForm.get('city').setValidators(null);
          self.profileForm.get('town').setValidators(null);
        }
        self.profileForm.get('zipcode').updateValueAndValidity();
        self.profileForm.get('city').updateValueAndValidity();
        self.profileForm.get('town').updateValueAndValidity();
      });
  }

Template

<mat-checkbox class="terms" formControlName="required_checkbox">Pickup Riraku</mat-checkbox>
		
<mat-form-field appearance="outline">
	<mat-label>Zip Code</mat-label>
	<input matInput type="text" formControlName="zipcode" placeholder="">
</mat-form-field>

<mat-form-field appearance="outline">
	<mat-label>City</mat-label>
	<input matInput type="text" formControlName="city" placeholder="">
</mat-form-field>

<mat-form-field appearance="outline">
	<mat-label>Town</mat-label>
	<input matInput type="text" formControlName="town" placeholder="">
</mat-form-field>

Solution 12 - Angular

To set the value in a checkbox the checkbox itself can have a value or not. So you can test on Validators.required and pass the value or true when checked and null or false if unchecked. And trigger the method onChangeInput :

public changeInput(event): void {
  this.isChecked = event.target.checked;
  // passing the value
  this.onChange(this.isChecked ? (this.value ? this.value : true) : false);
  // set touched
  if (!this.isTouched) {
    this.isTouched = true;
    this.onTouch();
  }
}

Solution 13 - Angular

Create a method to detect any changes

checkValue(event: any) {
    this.formulario.patchValue({
      checkboxControlName: event.target.checked
    })
}

Put that method on an event change and ngModel required properties

<input (change)="checkValue($event)" type="checkbox" formControlName="checkboxControlName" value="true" ngModel required>

And use the convetional way to validate

this.formulario = new FormGroup({
  checkboxControlName: new FormControl('', [Validators.required])
});

Source

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionnathasmView Question on Stackoverflow
Solution 1 - Angulardeveloper033View Answer on Stackoverflow
Solution 2 - AngularMicaView Answer on Stackoverflow
Solution 3 - AngularJavier GonzálezView Answer on Stackoverflow
Solution 4 - AngularMaximView Answer on Stackoverflow
Solution 5 - AngularmicronyksView Answer on Stackoverflow
Solution 6 - AngularValentin BossiView Answer on Stackoverflow
Solution 7 - AngularAjay ReddyView Answer on Stackoverflow
Solution 8 - AngularAntônio Carlos de L. Mendes JrView Answer on Stackoverflow
Solution 9 - AngularVIKAS KOHLIView Answer on Stackoverflow
Solution 10 - Angularaditya shribathoView Answer on Stackoverflow
Solution 11 - AngularRam PukarView Answer on Stackoverflow
Solution 12 - AngularRon JonkView Answer on Stackoverflow
Solution 13 - AngularWictor ChavesView Answer on Stackoverflow