最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to do validation with mat-checkbox? - Stack Overflow

programmeradmin0浏览0评论

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

}

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

}
Share Improve this question edited Feb 24, 2020 at 16:17 David Buck 3,82936 gold badges42 silver badges61 bronze badges asked Jun 19, 2018 at 19:14 MarckMarck 811 gold badge1 silver badge9 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 9

Use built-in validator: Validators.requiredTrue

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.

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 '';
  }
<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;
         }
发布评论

评论列表(0)

  1. 暂无评论