I need to validate a date of birth control of a reactive form, so if a user selected a value from the future, to disable the save button:
import { AbstractControl } from '@angular/forms';
export function validateDOB(control: AbstractControl)
{
let currentDateTime = new Date();
let monthValue = currentDateTime.getMonth()+1;
let formattedDate = currentDateTime.getFullYear() +'-'+ monthValue +'-'+currentDateTime.getDay();
let controlValue = control.value;
let monthOfControlValue = controlValue.getMonth()+1;
let FinalControlValue = controlValue.getFullYear()+'-'+monthOfControlValue+'-'+controlValue.getDay;
console.log(FinalControlValue)
if(formattedDate<control.value)
{
return {response: true};
}
return null;
}
Explanation:
I am working with angular material date picker, so the date will be displayed like the following:
Mon Oct 01 2018 00:00:00 GMT+0300 (Eastern European Summer Time)
the first 3 line are getting the current date and transforming it to YYYY-mm-dd
format:
let currentDateTime = new Date();
let monthValue = currentDateTime.getMonth()+1;
let formattedDate = currentDateTime.getFullYear() +'-'+
monthValue +'-'+currentDateTime.getDay();
The last 3 lines are converting the date selected by the user:
let monthOfControlValue = controlValue.getMonth()+1;
let FinalControlValue = controlValue.getFullYear()+'-'+monthOfControlValue+'-'+controlValue.getDay;
console.log(FinalControlValue )
At the user side, any date, whether it was less than or greater than, the validation will not work.
I tried to make the comparison without converting into YYYY-mm-dd
, but it didn't/wouldn't work.
I changed the script by changing the value of the control into a new date:
let controlValue = new Date(control.value);
And the script is now like:
import { AbstractControl } from '@angular/forms';
export function validateDOB(control: AbstractControl)
{
let currentDateTime = new Date();
let monthValue = currentDateTime.getMonth()+1;
let formattedDate = currentDateTime.getFullYear() +'-'+ monthValue +'-'+currentDateTime.getDay();
console.log(formattedDate)
let controlValue = new Date(control.value);
let monthOfControlValue = controlValue.getMonth()+1;
let FinalControlValue = controlValue.getFullYear()+'-'+monthOfControlValue+'-'+controlValue.getDay();
console.log(FinalControlValue)
if(formattedDate<control.value)
{
return {response: true};
}
return null;
}
And still not working.