我需要檢查一個人是否超過 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>
uj5u.com熱心網友回復:
首先,如果他們超過 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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/452958.html
