- 在组件中定义表单,包括开始日期和结束日期的FormControl对象,并指定验证规则。
import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
@Component({
selector: 'app-date-range-form',
template: `
`
})
export class DateRangeFormComponent {
dateRangeForm = new FormGroup({
startDate: new FormControl('', [Validators.required]),
endDate: new FormControl('', [Validators.required])
});
}
- 在组件模板中使用表单,并显示错误信息。
- 定义自定义验证器,用于验证开始日期是否早于结束日期。
import { ValidatorFn, AbstractControl } from '@angular/forms';
export function dateRangeValidator(): ValidatorFn {
return (control: AbstractControl): {[key: string]: any} | null => {
const startDate = control.get('startDate').value;
const endDate = control.get('endDate').value;
if (startDate && endDate && (new Date(startDate) > new Date(endDate))) {
return {dateRangeInvalid: true};
}
return null;
};
}
- 在表单中添加自定义验证器,用于验证开始日期是否早于结束日期。
import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { dateRangeValidator } from './date-range-validator';
@Component({
selector: 'app-date-range-form',
template: `