Warm tip: This article is reproduced from stackoverflow.com, please click
angular javascript typescript angular-material2

How to do validation with mat-checkbox?

发布于 2020-03-27 15:44:44

I would like to know how to check if the checkbox was selected, if it was not selected, an error message will appear for the user. I managed to put the error message but not to able to use it along with the rest of the form. can you help me? Here's what I have to do.

<mat-checkbox class="hcs-full-width" [formControl]="termsFormControl"> Aceite os termos de uso

</mat-checkbox>
<mat-error *ngIf="termsFormControl.hasError('required')">
    Termo é
    <strong>requirido</strong>
</mat-error>

.ts

export class AppComponent implements OnInit {

  private subscription: Subscription;
  uri: string;
  ssid: string;
  sessiondId: string;
  ip: string;
  mac: string;
  ufi: string;
  mgmtBaseUrl: string;
  clientRedirectUrl: string;
  req: string;
  userName: string;
  hmac: string;

  name: string;
  email: string;

  constructor(@Inject(DOCUMENT) private document: any, private route: ActivatedRoute) {
  }

  ngOnInit() {
    this.route.queryParams
      .filter(params => params.mac)
      .subscribe(params => {
        console.log(params);

        this.ssid = params.ssid;
        this.sessiondId = params.sessionId;
        this.ip = params.ip;
        this.mac = params.mac;
        this.ufi = params.ufi;
        this.mgmtBaseUrl = params.mgmtBaseUrl;
        this.clientRedirectUrl = params.clientRedirectUrl;
        this.req = params.req;
        this.hmac = params.hmac;
      });
      console.log("LOGAR: " + this.nameFormControl.valid);
    console.log("LOGAR: " + this.termsFormControl.valid);
  }

  Logar() {
    if (this.nameFormControl.valid && this.emailFormControl.valid && this.termsFormControl.valid) {
      this.userName = this.name + ";" + this.email;
      this.uri = "#" + this.ssid + "&sessionId=" + this.sessiondId + "&ip=" + this.ip + "&mac=" + this.mac + "&ufi=" + this.ufi + "&mgmtBaseUrl=" + this.mgmtBaseUrl + "&clientRedirectUrl=" + this.clientRedirectUrl + "&req=" + this.req + "&username=" + this.userName + "&hmac=" + this.hmac;
      // console.log("LOGAR: " + this.nameFormControl.valid);
      this.document.location.href = this.uri;
    }
    console.log("LOGAR: " + this.nameFormControl.valid);
    console.log("LOGAR: " + this.termsFormControl.valid);
  };

  emailFormControl = new FormControl('', [
    Validators.required,
    Validators.email,
  ]);

  nameFormControl = new FormControl('', [
    Validators.required,
  ]);

  termsFormControl = new FormControl('', [
    Validators.required,
  ]);

}
Questioner
Marck
Viewed
382
kat1330 2019-01-04 04:00

Checkbox doesn't work like that, you have to implement custom validator and assign to your termsFormControl. In your case it will be:

termsFormControl = new FormControl('', [(control) => {    
    return !control.value ? { 'required': true } : null;
  }]
);

Here custom validator explicitly checking value of control and if is false it will set required error to be true. On that way you can set state to your form and be able to consume powerful features.

Please see following issue on GitHub for more explanation why you have to implement custom validation.

EDITED 1

To show error message when button is clicked you can set condition to rise error when checkbox isinvalid and dirty:

<mat-error *ngIf="termsFormControl.invalid && termsFormControl.dirty">
        Termo é <strong>requirido</strong>
</mat-error>

Then on button click you can set checkbox to be dirty (I don't see your entire code but it should be something like this):

onSubmit() {
  this.form.get('termsFormControl ').markAsDirty();
}

EDITED 2

Based on @Julida suggestion built in validator Validators.requiredTrue is available for checkbox elements. It validate does checkbox is checked or unchecked. It marks control invalid if is unchecked.