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

Checking the correctness of a date from input type:"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;
}