簡體   English   中英

如何使用 mat-checkbox 進行驗證?

[英]How to do validation with mat-checkbox?

我想知道如何檢查復選框是否被選中,如果沒有被選中,將向用戶顯示一條錯誤消息。 我設法放置了錯誤消息,但無法將其與表單的 rest 一起使用。 你能幫助我嗎? 這是我必須做的。

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

}

使用內置驗證器:Validators.requiredTrue

復選框不能那樣工作,您必須實現自定義驗證器並分配給您的termsFormControl 在您的情況下,它將是:

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

這里自定義驗證器顯式檢查控件的值,如果為 false 則將required錯誤設置為true 通過這種方式,您可以為表單設置狀態並能夠使用強大的功能。

請參閱 GitHub 上的以下問題以獲取更多解釋為什么必須實施自定義驗證。

編輯 1

要在單擊按鈕時顯示錯誤消息,您可以設置條件以在復選框無效和臟時引發錯誤:

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

然后單擊按鈕,您可以將復選框設置為臟(我沒有看到您的整個代碼,但它應該是這樣的):

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

編輯 2

基於驗證Validators.requiredTrue內置的@Julida 建議Validators.requiredTrue可用於復選框元素。 它驗證是否選中或取消選中復選框。 如果未選中,它將標記控制無效。

Required在這種情況下不起作用,因為從技術上講false是一個值。 因此,您必須使用RequiredTrue ,例如:

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

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