Marck
Marck

Reputation: 81

How to do validation with mat-checkbox?

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,
  ]);

}

Upvotes: 5

Views: 17615

Answers (4)

Becario Senior
Becario Senior

Reputation: 714

Use built-in validator: Validators.requiredTrue

Upvotes: 9

EliuX
EliuX

Reputation: 12625

Required in this case won't work because technically speaking false is a value. So, you must use RequiredTrue, e.g.:

termsFormControl = new FormControl(false, [Validators.requiredTrue]);

Nonetheless, if you need to check whether this option has been checked, lets say to display a message, you must verify for the error of required:

  get acceptTermsErrorMessage() {
    if (this.form.hasError('required', 'termsFormControl')) {
      return "You must accept the terms and conditions in order to continue;
    }

    return '';
  }

Upvotes: 1

rohithd
rohithd

Reputation: 147

<mat-checkbox 
 (change)="todoItemSelectionToggle($event)">{{node.item}}</mat-checkbox>


        In .ts file if event.checked is true checkbox is selected else viceversa


         todoItemSelectionToggle(event)
         {
         console.log = event.checked;
         }

Upvotes: -1

kat1330
kat1330

Reputation: 5332

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.

Upvotes: 5

Related Questions