Angular – Age Validator
Table of Contents
Sources
Starter-Code
// age.validator.ts
import { FormControl, ValidatorFn, AbstractControl } from '@angular/forms';
import * as dayjs from 'dayjs';
export class AgeValidator {
static ageLimitValidator(minAge: number, maxAge: number): ValidatorFn {
return (control: AbstractControl): { [key: string]: any } | null => {
// get age form date
let age: number;
age = dayjs(Date.now()).diff(dayjs(control.value), 'year');
// if control value is not null and is a number
if (control.value !== null) {
// return null if it's in between the minAge and maxAge and is A valid Number
return isNaN(age) || // checks if its a valid number
age < minAge || // checks if its below the minimum age
age > maxAge // checks if its above the maximum age
? { ageLimit: true } // return this incase of error
: null; // there was not error
}
return null;
};
}
}
import { FormGroup, FormBuilder, FormControl, Validators } from '@angular/forms';
import { AgeValidator } from '../../validators/age.validator';
export class YourClass implements OnInit {
validationsForm: FormGroup;
validations = {
'birthdate': [
{ type: 'required', message: 'Age is required.' },
{ type: 'ageLimit', message: 'You have to be at least 18 years old' }
]
};
ngOnInit() {
this.validationsForm = new FormGroup({
'birthdate': new FormControl('', Validators.compose([
AgeValidator.ageLimitValidator(18, 60),
Validators.required]
))
});
}
}