Reputation: 1121
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
Yup.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?
Upvotes: 8
Views: 10929
Reputation: 1928
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.
import parse from "date-fns/parse";
function parseDateString(value, originalValue) {
return isDate(originalValue)
? originalValue // this make sure that a value is provided
: parse(originalValue, "yyyy-MM-dd", new Date());
}
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")
});
Upvotes: 2