简体   繁体   English

如何使用 mat-checkbox 进行验证?

[英]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.我设法放置了错误消息,但无法将其与表单的 rest 一起使用。 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 .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,
  ]);

}

使用内置验证器:Validators.requiredTrue

Checkbox doesn't work like that, you have to implement custom validator and assign to your termsFormControl .复选框不能那样工作,您必须实现自定义验证器并分配给您的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 .这里自定义验证器显式检查控件的值,如果为 false 则将required错误设置为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.请参阅 GitHub 上的以下问题以获取更多解释为什么必须实施自定义验证。

EDITED 1编辑 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编辑 2

Based on @Julida suggestion built in validator Validators.requiredTrue is available for checkbox elements.基于验证Validators.requiredTrue内置的@Julida 建议Validators.requiredTrue可用于复选框元素。 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. Required在这种情况下不起作用,因为从技术上讲false是一个值。 So, you must use RequiredTrue , eg:因此,您必须使用RequiredTrue ,例如:

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

N.netheless, 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 : N.netheless,如果你需要检查这个选项是否已经被选中,比如说显示一条消息,你必须验证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;
         }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM