Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DOB validation in Angular Reactive Form

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>
like image 521
Chris Avatar asked Oct 19 '25 10:10

Chris


1 Answers

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.

like image 81
Ankit Avatar answered Oct 22 '25 00:10

Ankit