从输入类型检查日期的正确性:"date" ts



我需要检查一个人是否超过18岁。

如果输入不正确,我想给一个带有注释的标签。它不起作用,我不知道问题出在哪里。

我写了这个函数来检查它:

import { AbstractControl } from "@angular/forms";
export function checkBirthDate(birthDateControl: AbstractControl): { [key: string]: boolean } | null {
let birthDate = new Date(birthDateControl.get('birthDate')?.value);
if (Math.abs((new Date().getFullYear() - birthDate.getFullYear()))> 18) {
return { birthDateError: true }
}
return {};
}

这是调用上面函数的代码:

ngOnInit(): void {
this.addVolunteerForm = new FormGroup({
firstName: new FormControl('', Validators.compose([Validators.required, Validators.maxLength(15),
Validators.pattern("^[a-z ]*$"), Validators.minLength(2)])),
lastName: new FormControl('', Validators.compose([Validators.required, Validators.maxLength(15),
Validators.pattern("^[a-z ]*$"), Validators.minLength(2)])),
birthDate: new FormControl('', Validators.compose([Validators.required])),
},
{ validators: checkBirthDate } // <- the call
)
}

这是输入:

<label for="bd">Date Of Birth</label>
<input type="date" class="form-control" id="bd" #db placeholder="Birth Date" formControlName="birthDate">
<p *ngIf="addVolunteerForm.errors?.['birthDateError']" class="text-danger">  
You're still young wait a little longer   
</p>

首先,如果他们超过18岁,你会给出一个错误,但通过你的消息,你想检查他们是否低于18岁。逻辑也有点缺陷,因为你不能只按年份计算,你还需要考虑月份和日期。只需使用unix时间戳进行此类计算。

export function checkBirthDate(
birthDateControl: AbstractControl
): ValidationErrors | null {
const eighteenYearsInMillis = 5.67648e11;
let birthDate = new Date(birthDateControl.get('birthDate')?.value);
if (
new Date().getTime() - new Date(birthDate).getTime() <
eighteenYearsInMillis
)
return { birthDateError: true };
return null;
}

最新更新