使用Angular反应形式验证年龄是否超过18岁 [英] Validate if age is over 18 years old with Angular Reactive Forms

查看:161
本文介绍了使用Angular反应形式验证年龄是否超过18岁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Angular Validators输入用户的出生日期时,是否可以检查用户是否超过18岁?

Is there a way to check if a user is over 18 years of age when they have entered their date of birth using Angular Validators?

我的表单如下:

<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>

然后在TS文件中设置以下验证器:

And then I have these validators set in the TS file:

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)]));
 }

因此,如果验证器中满足上述条件,该按钮将变为启用状态.但是我还需要在启用输入日期之前检查输入的日期是否已超过18年.由于日期是通过3个输入(dd,mm,yyyy)输入的,因此这似乎很棘手.在这种情况下,我不能使用输入日期标签.任何建议或意见表示赞赏.谢谢!

So if the conditions above are satisfied in the Validators, the button becomes enabled. But I also need to check that the entered date is over 18 years old before enabling it. This seems tricky as the date is entered via 3 inputs (dd, mm, yyyy). And in this case, I can't use the input date tag. Any suggestions or comments appreciated. Thanks!

P.S.感谢您提供有关使用MomentJS的所有建议.我已经在应用程序的其他地方使用了它,所以我也会在这里使用它.

推荐答案

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

You need to configurate a custom validator that will be hooked to the complete FormGroup in this case. A momentjs based approach would look like this:

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));
  }
}

有关实时示例,请在此处查看

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

Notice that in this case Im not taking care of any format/range validation on the singular input fields.

这篇关于使用Angular反应形式验证年龄是否超过18岁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆