Reputation: 2647
In Angular-12, I am using Material datepicker for date of birth:
Component:
tomorrow = new Date();
constructor(
private router: Router,
) {
this.tomorrow.setDate(this.tomorrow.getDate());
}
HTML
<div class="col-12 col-md-6">
<label for="dob">Date of Birth:<span style="color:red;">*</span></label>
<div class="form-group">
<mat-form-field fxFlex="100%" fxFlex.gt-sm>
<input matInput [matDatepicker]="dob" placeholder="Choose a date" [max]="tomorrow" formControlName="dob" readonly required>
<mat-datepicker-toggle matSuffix [for]="dob"></mat-datepicker-toggle>
<mat-datepicker #dob></mat-datepicker>
</mat-form-field>
</div>
<div *ngIf="fp.dob.touched && fp.dob.invalid">
<div *ngIf="fp.dob.hasError('required')">
<div class="text-danger">
Date of Birth is required!
</div>
</div>
</div>
</div>
I want to set the min date to 18 years so that any candidate below 18 years will not be able to register.
How do I achieve this?
Thanks
Upvotes: 1
Views: 3684
Reputation: 194
If you want to limit it to 18 year olds. You actually want to set the max to todays date minus 18 years, not the min.
In your component constructor something like this(although I would recommend you use ngOnInit instead for components).
maxDob: Date;
constructor(
private router: Router,
) {
const today = new Date();
this.maxDob = new Date(
today.getFullYear() - 18,
today.getMonth(),
today.getDate()
);
}
And make sure to change your html as well
<input matInput [matDatepicker]="dob" placeholder="Choose a date" [max]="maxDob" formControlName="dob" readonly required>
Here's a stackblitz example with ngOnInit
https://stackblitz.com/edit/angular-material-4erepd?file=app/app.component.ts
Upvotes: 2
Reputation: 916
Use the [max]
to compute maximum value for the date picker.
Component
export class DatepickerMinMaxExample implements OnInit {
maxDate: Date;
date: Date;
ngOnInit(): void {
this.maxDate = new Date();
this.maxDate.setMonth(this.maxDate.getMonth() - 12 * 18);
}
}
Template
<mat-form-field class="example-full-width">
<input matInput #input="ngModel" [(ngModel)]="date" [min]="minDate" [max]="maxDate" [matDatepicker]="picker" placeholder="Choose a date">
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
<mat-error *ngIf="input.hasError('matDatepickerMax')">Date should be inferior</mat-error>
</mat-form-field>
Here is a Working Demo
Upvotes: 1