I believe that for the date().max()
, we should pass the maximum date with the following format YYYY-MM-DD
(year-month-day) for the method max()
. In this case we could use the method toLocaleDateString
which would come in the following format, for example, "08/02/2021"
and make some manipulations to get to the format that Yup accepts.
We will make:
const currentDate = new Date().toLocaleDateString();
const dateFormated = currentDate.split('/').reverse().join('-');
console.log('Data formatada: ', dateFormated);
From this code, we can create a function that will be used by Yup when validating the date field.
Let’s call it getFormatedDate
:
const getFormatedDate = (currentDate) => {
return currentDate.split('/').reverse().join('-');
}
This function expects to receive a date in the format "08/02/2021"
, soon as we call her inside the max()
, we should spend a new Date().toLocaleDateString()
parameter:
const getFormatedDate = (currentDate) => {
return currentDate.split('/').reverse().join('-');
}
export const UserSchema = Yup.object({
date: Yup.date().max(getFormatedDate(new Date().toLocaleDateString())).required("Campo obrigatório")
});
Now every time we validate a date, it will have the maximum value of this moment.
If you also want to know, to give a minimum acceptable date, the same logic would be repeated, just enter the date string in the correct format:
// não aceita datas inferiores a 1 de Janeiro de 1900
date: Yup.date().min(getFormatedDate('01/01/1900')).required("Campo obrigatório")