Skip to content

isValid cannot leave field blank #2952

Answered by fturmel
jshsmth asked this question in Q&A
Discussion options

You must be logged in to vote

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 parse function in v1 doesn't support format tokens, it's essentially parseISO from v2: https://date-f…

Replies: 2 comments 6 replies

Comment options

You must be logged in to vote
1 reply
@jshsmth
Comment options

Comment options

You must be logged in to vote
5 replies
@jshsmth
Comment options

@fturmel
Comment options

@jshsmth
Comment options

@fturmel
Comment options

@jshsmth
Comment options

Answer selected by jshsmth
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants