FormBuilder 中的空控件根对象

Empty control root object in FormBuilder

我有以下表格:

return this.fb.group({

      'day':['', [Validators.required, Validation.ruleLeaveValidator]],
      'month': ['', []],
      'year': ['', [Validators.maxLength(4), Validators.min(1920)
    });

和自定义规则验证 ruleLeaveValidator:

static ruleLeaveValidator(control: FormControl): ValidationErrors | null {
    console.log(root.controls);
}

为什么没有对象root.controls

你可以在这里使用control

static ruleLeaveValidator(control: FormControl) {
    console.log(control.value);

        if (control.value != null) {
            const matches = 'your_date_validation;
            return matches ? null : { 'invaliddate': true };
        } else {
            return null;
        }
}

虽然我不知道你使用的方式,但你也可以像这样进行自定义验证:

private ruleLeaveValidator(): ValidatorFn {
    return (control: AbstractControl): Observable<{ [key: string]: any }> => {
        if(checkIsInvalid)
        {
            return { 'errorName': true };
        } else {
            return null;
        }
    };
}

并像这样使用:

return this.fb.group({
  'day':['', [Validators.required], this.ruleLeaveValidator()],
  'month': ['', []],
  'year': ['', [Validators.maxLength(4), Validators.min(1920)
});