I need to check if a person is older than 18.
If the input is incorrect I want to give a tag with a comment. It does not work and I can not figure out what the problem is.
i wrote this function that checks it:
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 {};
}
this is the code that calls the function above:
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
)
}
and this is the input:
<label for="bd">Date Of Birth</label>
<input type="date" id="bd" #db placeholder="Birth Date" formControlName="birthDate">
<p *ngIf="addVolunteerForm.errors?.['birthDateError']" >
You're still young wait a little longer
</p>
CodePudding user response:
Firstly you're giving an error if they're over 18, but by your message you want to check if they're under 18. The logic is a bit flawed as well since you can't just go by the year, you need to take into account the month and day as well. Just use unix timestamps for these kinds of calculations.
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;
}