I stumbled upon an interesting function in another post that checks whether a person is 18 years old or older. I would like to convert and store the age in the backend separately, but the challenge is that I don't have an age input in the HTML. Here's the code snippet:
this.SignupForm = new FormGroup({
'username': new FormControl(null, [Validators.required
]),
'email': new FormControl(null, [Validators.required, Validators.email], this.forbiddenEmails),
'password': new FormControl(null, [Validators.required,Validators.minLength(4)
]),
'day': new FormControl(null, [Validators.required, Validators.maxLength(2),
]),
'month': new FormControl(null, [Validators.required, Validators.maxLength(2)
]),
'year': new FormControl('', [Validators.required, Validators.maxLength(4), Validators.minLength(4)
]),
});
this.SignupForm.setValidators(this.minimumAge(18));
}
private minimumAge(age: number): ValidatorFn {
return (fg: FormGroup): ValidationErrors => {
let result: ValidationErrors = null;
if (fg.get('year').valid && fg.get('month').valid && fg.get('day').valid) {
const value: { year: string, month: string, day: string } = fg.value;
const date = moment({ year: +value.year, month: (+value.month) - 1, day: +value.day }).startOf('day');
if (date.isValid()) {
const now = moment().startOf('day');
const yearsDiff = date.diff(now, 'years');
if (yearsDiff > -age) {
result = {
'minimumAge': {
'requiredAge': age,
'actualAge': yearsDiff
}
};
}
}
}
return result;
}
}
ngOnInit(): void {
this.SignupForm.statusChanges.subscribe(res => if(status == 'VALID'){
let day = this.SignupForm.get('day').value;
let month = this.SignupForm.get('month').value;
let year = this.SignupForm.get('year').value;
let age = (new Date().getYear()-new Date(year,month,day,0,0,0).getYear());
}
}
signupUser() {
this.authService.registerUser(this.SignupForm.value).subscribe(
data => {
this.tokenService.SetToken(data.token);
this.SignupForm.reset();
setTimeout(() => {
this.router.navigate(['posts']);
}, 3000);
},
err => {
if (err.error.msg) {
this.errorMessage = err.error.msg[0].message;
}
if (err.error.message) {
this.errorMessage = err.error.message;
}
}
);
}
Is there a way to extract the converted age value from this TypeScript function and send it to the database without using an age input field in the HTML?