使用 Angular Reactive Forms 验证年龄是否超过 18 岁

Jos*_*ose 2 validation date angular angular-reactive-forms

有没有办法在用户使用 Angular 验证器输入出生日期时检查用户是否已年满 18 岁?

我的表格如下所示:

<form [formGroup]="authForm" (ngSubmit)="submitForm()">
    <label>Date of birth</label>
    <input formControlName="day" maxlength="2" placeholder="DD" type="text" />
    <input formControlName="month" maxlength="2" placeholder="MM" type="text" />
    <input formControlName="year" maxlength="4" placeholder="YYYY" type="text" />
    <button [disabled]="!authForm.valid" type="submit"> Check age </button>
</form>
Run Code Online (Sandbox Code Playgroud)

然后我在 TS 文件中设置这些验证器:

if (this.authType === 'register') {
    this.authForm.addControl('year', new FormControl('', [Validators.required, Validators.maxLength(4), Validators.minLength(4)]));
    this.authForm.addControl('month', new FormControl('', [Validators.required, Validators.maxLength(2)]));
    this.authForm.addControl('day', new FormControl('', [Validators.required, Validators.maxLength(2)]));
 }
Run Code Online (Sandbox Code Playgroud)

因此,如果验证器中满足上述条件,则该按钮将启用。但我还需要在启用之前检查输入的日期是否超过 18 岁。这看起来很棘手,因为日期是通过 3 个输入(dd、mm、yyyy)输入的。在这种情况下,我无法使用输入日期标签。任何建议或意见表示赞赏。谢谢!

PS 感谢您对使用 MomentJS 的所有建议。我已经在应用程序的其他地方使用它,所以我也会在这里使用它。

Jot*_*edo 5

在这种情况下,您需要配置一个将连接到完整的自定义验证器FormGroup基于momentjs的方法如下所示:

export function minimumAge(age:number): ValidatorFn {
  return (fg: FormGroup): ValidationErrors => {
      let result: ValidationErrors = null;
      if (fg.get('year').valid && fg.get('month').valid && fg.get('day').valid) {
        // carefull, moment months range is from 0 to 11
        const value: { year: string, month: string, day: string } = fg.value;
        const date = moment({ year: +value.year, month: (+value.month) - 1, day: +value.day }).startOf('day');
        if (date.isValid()) {
          // https://momentjs.com/docs/#/displaying/difference/
          const now = moment().startOf('day');
          const yearsDiff = date.diff(now, 'years');
          if (yearsDiff > -age) {
            result = {
              'minimumAge': {
                'requiredAge': age,
                'actualAge': yearsDiff
              }
            };
          }
        }
      }
      return result;
    };
}

export class DateEditComponent {
  readonly authForm: FormGroup;

  constructor(private _fb: FormBuilder) {
    this.authForm = this._fb.group({
        year: ['', [Validators.required, Validators.maxLength(4), Validators.minLength(4)]],
        month: ['', [Validators.required, Validators.maxLength(2)]],
        day: ['', [Validators.required, Validators.maxLength(2)]]
    });
    this.authForm.setValidators(minimumAge(18));
  }
}
Run Code Online (Sandbox Code Playgroud)

有关实例,请查看此处

请注意,在这种情况下,我不处理单个输入字段的任何格式/范围验证。