如何向 angular 中的表单添加验证?

how to add validation to form in angular?

我有 2 个反应形式的输入。例如:生日和日期,我想为日期添加验证,该日期的最小值必须是生日或更多。我该如何解决? 我尝试这种方式,但它不起作用。 Validators.min(this.myForm.value.birthDate);

如果您附上 Typescript 文件会更有帮助,但我在这里附上自定义验证器的代码。请根据您的代码调整表格,字段的名称。简而言之,对于这些类型的验证,您必须编写自定义验证。内置验证在这里无济于事。

export class CustomeDateValidators {
    static fromToDate(fromDateField: string, toDateField: string, errorName: string = 'fromToDate'): ValidatorFn {
        return (formGroup: AbstractControl): { [key: string]: boolean } | null => {
            const fromDate = formGroup.get(fromDateField).value;
            const toDate = formGroup.get(toDateField).value;
           // Ausing the fromDate and toDate are numbers. In not convert them first after null check
            if ((fromDate !== null && toDate !== null) && fromDate > toDate) {
                return {[errorName]: true};
            }
            return null;
        };
    }
}

/*--- implementations ---*/
this.form = this.fb.group({
  fromDate: null,
  toDate: null,
}, { validator: [
  //Default error with this validator:  {fromToDate: true}
  CustomeDateValidators.fromToDate('fromDate', 'toDate')
  
  // For custome error name like: {customeErrorName: true}, pass third optional parameter with custome name
  // CustomeDateValidators.fromToDate('fromDate', 'toDate', 'customeErrorName')
]});