Reputation: 365
I need to validate that a user has checked a "TOS" checkbox before allowing their registration. I would like to use the requiredTrue validator for doing it, but I can't find in the docs a way of using this validator in a template driven form. Is it possible? If so, could you provide an example?
Upvotes: 3
Views: 10509
Reputation: 143
Like @braden-w said you can use requiredTrue
like the required
directive:
<input type="checkbox" name="TOS" ngModel requiredTrue>
I had a problem in Ionic, where the requiredTrue
directive was not working on an <ion-checkbox>
tag. It had the exact same functionality than required
. Therefore I created my own checkboxRequiredTrue
directive. It somehow works, if I call the Validators.requiredTrue
inside this directive.
@Directive({
selector: '[checkboxRequiredTrue]',
providers: [
{
provide: NG_VALIDATORS,
useExisting: CheckboxRequiredTrueDirective,
multi: true,
},
],
})
export class CheckboxRequiredTrueDirective implements Validator {
validate(control: FormControl): ValidationErrors | null {
return Validators.requiredTrue(control);
}
}
Upvotes: 0
Reputation: 91
When validating whether a checkbox has been selected with angular form validation, you can just add the "required" validator. This works for both template driven and reactive forms. For template driven forms your html for the checkbox would look something like this:
<input type="checkbox" name="TOS" ngModel required>
Or if you are using angular material:
<mat-checkbox name="TOS" ngModel required></mat-checkbox>
Both of the above examples will set the form validity to INVALID until the user checks the checkbox.
Upvotes: 0