如何验证数据来自 2 个输入的表单?

How do I validate a form where the data comes from 2 inputs?

相关案例:日期和时间。我的表单有 2 个单独的 input 字段,date(打开日期选择器)和 timeOfDay(打开时钟选择器),

<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]],
        ...
    })
}

我需要确保用户不能输入未来的日期和时间,但我一次只能验证一个输入,当然,这是行不通的。我该怎么做?

您可以创建一个接受其他控件作为输入的自定义验证器。像这样:

 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,
            ...
        })