-
Hey Everyone, Wondering if anyone is able to help out, I am using the isValid function along with parse and returning either "Date is invalid" or undefined But I would like it to not throw an error when the field is left blank as its an optional field. This is what I got so far. export const isValidDate = value => value && (!isValid(parse(value, 'dd/MM/yyyy', new Date())) ? 'Date is Invlaid' : undefined) |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 6 replies
-
Can you give an input example to your function that throws an error? Also, please confirm which version of |
Beta Was this translation helpful? Give feedback.
-
Just check if the input is empty before passing to parse? Something like this? import { isValid, parse } from "date-fns";
export const isValidDateOrEmpty = (value) =>
!value || isValid(parse(value)) ? undefined : "Date is invalid";
console.log(isValidDateOrEmpty("bad input")); // "Date is invalid"
console.log(isValidDateOrEmpty(null)); // undefined
console.log(isValidDateOrEmpty(undefined)); // undefined
console.log(isValidDateOrEmpty("")); // undefined
console.log(isValidDateOrEmpty("04/02/2022")); // undefined EDIT 1: using v1 syntax Please reference the v1 version of the docs, the EDIT 2: slightly better code |
Beta Was this translation helpful? Give feedback.
Just check if the input is empty before passing to parse? Something like this?
EDIT 1: using v1 syntax
Please reference the v1 version of the docs, the
parse
function in v1 doesn't support format tokens, it's essentiallyparseISO
from v2: https://date-f…