2017-07-28 38 views

回答

0

讓我們假設您是否輸入PIN碼,confirmmpin是必須的(反之亦然)否則無需對兩者進行必要的驗證。

代碼:

this.UserForm = this.fb.group({ 
     .... 
     .... 
     security: this.fb.group({ 
      pin: [this.securityobj.pin], 
      confirmpin: [this.securityobj.confimrpin] 
     }, {validator: abhimatcher}) 

    }); 

的CustomValidator

export const customValidator= (control: AbstractControl): { [key: string]: boolean } => { 
    const initalText = control.get('pin'); 
    const requiredText = control.get('confirmpin'); 

    if (initalText || requiredText) 
     return null; 

    else 
     return { customValidate: true }; 
} 

HTML

 <form [formGroup]="UserForm" novalidate (ngSubmit)="onSubmit(UserForm)"> 
      ..... 
      ..... 
      <input type="password" class="form-group" formControlName="pin"> 
          <div *ngIf="UserForm.get('security').hasError('customValidate') && UserForm.get('security').get('pin').touched" class="text-danger"> 
           pin is required! 
          </div> 
         </div><br /> 
         <div> 
          <label class="center-block">ConfirmPin:</label> 
          <input type="password" class="form-group" formControlName="confirmpin"> 
         </div> 
         <div *ngIf="UserForm.get('security').hasError('customValidate') && UserForm.get('security').get('confirmpin').touched" class="text-danger"> 
          pin is required! 
         </div> 
     <button type="submit" class="btn btn-default" [disabled]="UserForm.invalid">Submit</button> 
</form> 
相關問題