'Yup.date() convert date into string without timezone after validation
I using Yup with react-hook-form and have the following schema in Yup
const validationSchema = Yup.object({
installation: Yup.string().nullable().required("Required"),
from_date: Yup.date()
.max(new Date(), "Cannot use future date")
.nullable()
.required("Required"),
to_date: Yup.date()
.min(Yup.ref("from_date"), "To Date cannot be before From Date")
.max(new Date(), "Cannot use future date")
.nullable()
.required("Required")
});
When I type the date in the inputs, the validation is working perfectly but the date is being returned in the format 2021-03-31T18:30:00.000Z, however I want the date to be returned just as 2021-03-31.
I am sending the data to a Django backend server and that expects just a DateField without the timezone. How should I do this?
Is there any way to convert the date without the timezone. I can get it working if I use Yup.string() instead, but then the necessary validation would not work.
Possible Solution Idea (But need help to understand how to do it)
Can I write some custom validation in Yup. If that is possible then i could use Yup.string() and still perform the necessary validation
- Use
Yup.string() - Convert to date
- Perform the necessary validation
- Reconvert date to string
- And return string
P.S This question has had many views but no significant comments or answers. Can I change the question formatting to make it more understandable?
Solution 1:[1]
You should write a quick function in order to change the format before to go head with further validation of yup.
In order to do that you can use date-fns helper.
function parseDateString(value, originalValue) {
const parsedDate = isDate(originalValue)
? originalValue // this make sure that a value is provided
: parse(originalValue, "yyyy-MM-dd", new Date());
return parsedDate;
}
Than can be used in this way:
import { date, object } from "yup";
const today = new Date();
const validationSchema = Yup.object({
installation: Yup.string().nullable().required("Required"),
from_date: Yup.date()
.transform(parseDateString)
.max(new Date(), "Cannot use future date")
.required("Required"),
to_date: Yup.date()
.min(Yup.ref("from_date"), "To Date cannot be before From Date")
.max(new Date(), "Cannot use future date")
.required("Required")
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
