Last active
September 3, 2021 22:54
-
-
Save anrras/b871f2669f205b635aa80089d7510214 to your computer and use it in GitHub Desktop.
Angular custom validations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { AbstractControl, FormGroup, ValidationErrors, ValidatorFn } from '@angular/forms'; | |
export class CustomValidators { | |
static age(control: AbstractControl) { | |
const value = control.value; | |
if (value < 18) { | |
return { isYoung: true }; | |
} | |
return null; | |
} | |
static ageWithParam(max: number) { | |
return (control: AbstractControl) => { | |
const value = control.value; | |
if (value < max) { | |
return { isYoung: true }; | |
} | |
return null; | |
}; | |
} | |
static validateActualDate( | |
control: AbstractControl | |
): { [key: string]: boolean } | null { | |
const currentDate = new Date(); | |
const value = control.value; | |
let valueToDate = new Date(); | |
if (value) { | |
valueToDate = new Date(value); | |
if (valueToDate > currentDate) { | |
return { dateInvalid: true }; | |
} | |
} | |
return null; | |
} | |
atLeastOneTimeLimitValidator: ValidatorFn = ( | |
formGroup: FormGroup | |
): ValidationErrors | null => { | |
const minTimeLimitControl = formGroup.get('minTimeLimit'); | |
const maxTimeLimitControl = formGroup.get('maxTimeLimit'); | |
const objValidator = { minTimeLimitControl, maxTimeLimitControl }; | |
let theOne = Object.keys(objValidator).findIndex( | |
(key) => objValidator[key].value !== '' | |
); | |
if (theOne === -1) { | |
console.log(theOne); | |
return { atLeastOneTimeLimitValidator: true }; // This is our error! | |
} else { | |
return null; | |
} | |
}; | |
static dateMinMaxValidator(control: AbstractControl) { | |
const value = control.value; | |
if (!value) { | |
return null; | |
} | |
const year = new Date(); | |
const actualYear = new Date(year).getFullYear(); | |
const valueYear = new Date(value).getFullYear(); | |
const validMaxYear = Number(actualYear) + 100; | |
const validMinYear = Number(actualYear) - 100; | |
if (valueYear > validMaxYear) { | |
return { | |
dateMinMax: true, | |
}; | |
} | |
if (valueYear < validMinYear) { | |
return { | |
dateMinMax: true, | |
}; | |
} | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment