簡體   English   中英

如何觸發自定義和內置驗證器以在ng2模板表單上進行驗證?

[英]How can I trigger custom and built in validators to validate on an ng2 template form?

我有一個帶有以下控件的ng2表單:

<input class="form-field"
     type="text"
     id="fieldName"
     name="fieldName"
     #fieldName="ngModel"
     (ngModelChange)="onFieldNameChange($event)"
     [(ngModel)]="model.fieldName"
     [ngModelOptions]="{updateOn: 'blur'}"
     suCustomValidator="message"
     [suAnotherCustomValidator]="booleanConditionInComponentTs">

(其中su是我的自定義組件的前綴)

作為模板表單的一部分。

驗證器和自定義驗證器在什么時候觸發? 如何在更改另一個字段時以及通過觸摸該字段來強制驗證該字段?

由於不清楚您的要求,因此您需要為每個字段都具有本地自定義驗證器,而對於字段具有相互影響,則需要全局驗證器。

一個很好的例子是passwordrepeat password字段

private buildForm(): void {
    this.form = this.fb.group({
      password: [null, Validators.required], // define password field to be mandatory (can have custom validator func call too) 
      repeat: [null, Validators.required]// define repeat password field to be mandatory (can have custom validator func call too)
    }, {validator: this.matchingPasswords('password', 'repeat')}); // have global validator to check when inputs are mades
}


private matchingPasswords(password: string, repeat: string) {
    return (group: FormGroup) => {
      const passwordIn = group.controls[password];
        const repeatIn = group.controls[repeat];
      if (passwordIn.value !== repeatIn.value) {
        return repeatIn.setErrors({notEquivalent: true});
      } else {
        return repeatIn.setErrors(null);
      }
    };
  }

在html模板中

    <p *ngIf="form.get('repeat')?.errors?.notEquivalent">Passwords did not match</p>
    <p *ngIf="form.get('repeat')?.errors?.required">Confirm password is required</p>
    <p *ngIf="form.get('password')?.errors?.required">Password is required</p>

很少有用的鏈接:

在提交表單時觸發驗證

使用多格式字段的自定義驗證

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM