I am trying to validate date of birth in Angular 2+ reactive form. I want to show error message when the selected DOB date is more than 100 years old.
Front end side
<div [ngClass]="setClassDOB()">
<input class="form-control" type="date"name="dob"formControlName="dob" placeholder="DOB">
</div>
Do this in your .html file : And now design the form below the above div tag (in.html file): Try this one:
<input type="date" formControlName="dateOfBirth" />
<div *ngIf="form.get('dateOfBirth').errors?.invalidDateOfBirth">
Please enter a valid date of birth (minimum age is 18).
</div>
In your .ts file:
import { FormControl, FormGroup, FormBuilder } from '@angular/forms';
export class MyComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = fb.group({
dateOfBirth: ['', validateDateOfBirth],
});
}
function validateDateOfBirth(control: FormControl): { [key: string]: any } | null {
const dateOfBirth = control.value;
const age = calculateAge(dateOfBirth);
// check if date is valid and person is at least 18 years old
if (isNaN(dateOfBirth.getTime()) || age < 18) {
return { 'invalidDateOfBirth': true };
}
return null;
}
function calculateAge(birthday: Date) {
const ageDifMs = Date.now() - birthday.getTime();
const ageDate = new Date(ageDifMs);
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
}
Try this out.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With