2016-09-08 43 views
0

有問題的情況:日期和時間。我的形式有2個獨立的input領域,date(打開日期選擇器)和timeOfDay(打開時鐘選擇器),如何驗證數據來自2個輸入的表單?

<div class="form-group date-and-time"> 
    <div class="my-datepicker md-form-control"> 
     <md-input readOnly type="text" placeholder="Date" myDatePicker formControlName="date"> 

     </md-input> 
     <small *ngIf="!form.controls.date.valid && submitted" class="ui error-message"> 
      Invalid date. 
     </small> 
    </div> 
    <div class="my-clockpicker md-form-control"> 
     <md-input readOnly type="text" placeholder="Time" myClockPicker formControlName="timeOfDay"> 

      <span md-suffix>'Clock</span> 
     </md-input> 
     <small *ngIf="!form.controls.timeOfDay.valid && submitted" class="ui error-message"> 
      Invalid time. 
     </small> 
    </div> 
</div> 

private _initForm() { 
    let now = moment(); 
    this.submitted = false; 
    this.form = this.formBuilder.group({ 
     date: [now.format('DD.MM.YYYY'), [<any>Validators.required]], 
     timeOfDay: [now.format('HH:mm'), [<any>Validators.required]], 
     ... 
    }) 
} 

我需要確保用戶可以不輸入將來的日期和時間,但我一次只能驗證一個輸入,這當然不起作用。我如何去做這件事?

回答

2

您可以創建一個自定義驗證程序,將接受另一個控件作爲輸入。事情是這樣的:

export class CustomValidators { 

    static futureDated(
     thePassedInControl: AbstractControl) { 
     return function (theValidatedControl) { 
      return new Promise(resolve => { 

      var futureDated = false; 
      //determine which control is date, and which is time 
      //determine if future dated 
      //... 

      if (futuredated) { 

       resolve({ 'futureDated': true }); 
      } 
      else { 
       resolve(null); 
      } 
     }); 
     }; 
    }; 
} 

然後,您可以使用此驗證兩個控件:

this.date = new FormControl(now.format('DD.MM.YYYY'), <any>Validators.required); 
this.timeOfDay = new FormControl(now.format('HH:mm'), <any>Validators.required);   

//set custom validators 
this.date.setAsyncValidators(CustomValidators.futureDated(this.timeOfDay)); 
this.timeOfDay.setAsyncValidators(CustomValidators.futureDated(this.date)); 

this.form = this.formBuilder.group({ 
      date: this.date, 
      timeOfDay: this.timeOfDay, 
      ... 
     })