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);
}
}
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
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')]
});
<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() {
}
}