目前我正在使用此代码 当用户在datepicker中选择出生日期时,此功能会计算它,如果大于18,则禁用保存按钮 问题是,当我选择年龄低于18岁时,不会考虑电子邮件ID下方字段的验证,并且表单会被提交。
Compnent.ts代码:
checkAge(event) {
var element = <HTMLInputElement> document.getElementById("submit");
//get date of birth of family members
this.userFamilyForm.get('dob').valueChanges.subscribe((dob: any) => {
let todayDate = new Date();
var dobDate = new Date(dob);
this.years = Math.floor((todayDate.getTime() - dobDate.getTime()) / (365.25 * 24 * 60 * 60 * 1000));
if (this.years >= 18) {
element.disabled = true;
this.userFamilyForm.get('email').setValidators(Validators.compose([CustomValidators.required, CustomValidators.checkEmail]));
}
else {
element.disabled = false;
this.userFamilyForm.get('email').setValidators(Validators.nullValidator);
}
});
}
HTML表单:
<div class="col-md-5 no-pd">
<div class="form-group">
<label for="dob" class="required">
{{'userFamily.labels.DATE_OF_BIRTH' | translate}}
</label>
<p class="input-group">
<input type="text" class="form-control" placeholder="{{'userFamily.placeholder.DATE_OF_BIRTH' | translate}}" bsDatepicker
#drp="bsDatepicker" formControlName="dob" [maxDate]="maxDate" (ngModelChange)="checkAge($event)" />
<span class="input-group-btn">
<a class="btn btn-default" (click)="drp.toggle()">
<em class="fa fa-calendar"></em>
</a>
</span>
<span class="text-danger" *ngIf="userFamilyForm.controls['dob'].hasError('required') && userFamilyForm.controls['dob'].hasError('required') && (userFamilyForm.controls['dob'].touched || userFamilyForm.controls['dob'].touched)">
{{'userFamily.errors.DOB_PHN_REQUIRED' | translate}}
</span>
</div>
<div class="form-group">
<label for="email" class="required">
{{'userFamily.labels.EMAIL' | translate}}
</label>
<input type="email" class="form-control" formControlName="email" id="email">
<span class="text-danger" *ngIf="userFamilyForm.controls['email']?.errors?.checkRequired && userFamilyForm.controls['email'].touched">{{'userFamily.errors.EMAIL_ERROR_VALID' | translate}}</span>
<span class="text-danger" *ngIf="!userFamilyForm.controls['email']?.errors?.checkRequired && userFamilyForm.controls['email']?.errors?.checkEmail && (userFamilyForm.controls['email'].dirty || userFamilyForm.controls['email'].touched)">{{'userFamily.errors.EMAIL_ERROR' | translate}}</span>
</div>