【发布时间】:2018-05-11 07:25:27
【问题描述】:
有没有办法在用户使用 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>
然后我在 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)]));
}
因此,如果验证器中满足上述条件,则按钮将变为启用状态。但我还需要在启用之前检查输入的日期是否超过 18 岁。这似乎很棘手,因为日期是通过 3 个输入(dd、mm、yyyy)输入的。在这种情况下,我不能使用输入日期标签。任何建议或 cmets 表示赞赏。谢谢!
附注感谢所有关于使用 MomentJS 的建议。我已经在应用程序的其他地方使用了它,所以我也会在这里使用它。
【问题讨论】:
-
嘿,你可以使用 moment.js 来编写@joto.toledo 提到的日期验证,更多参考momentjs.com
标签: angular validation date angular-reactive-forms