Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Requiring a checkbox to be checked

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);   } } 
like image 229
nathasm Avatar asked Feb 17 '16 16:02

nathasm


People also ask

How do I make a checkbox automatically checked?

Add checked = "checked" to the input you want selected. For XHTML the recommended way is as described. Check HTML manual and W3C to confirm. The markup posted isn't XHTML, so it's logical to use just the simple keyword attribute checked .

Does required attribute work for checkbox?

The required property sets or returns whether a checkbox must be checked before submitting a form. This property reflects the HTML required attribute.


2 Answers

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

like image 71
developer033 Avatar answered Oct 06 '22 11:10

developer033


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')]     }); 
like image 45
Mica Avatar answered Oct 06 '22 11:10

Mica