Receive a string and verify if it is a valid date with date-fns

Viewed 22213

I just want to validate if the string that i received is a valid date using date-fns. I gonna receive a date like this '29/10/1989', BR date. I want to transform it into 29-10-1989 and check if its valid. Anyone can help me with this?

const parsedDate = parseISO('29/10/1989')

this code above doesnt work, i got 'Invalid Date'

2 Answers

Try parse with locale options like this:

import { parse, isValid, format } from 'date-fns';
import { enGB } from 'date-fns/locale';

const parsedDate = parse('29/10/1989', 'P', new Date(), { locale: enGB });
const isValidDate = isValid(parsedDate);
const formattedDate = format(parsedDate, 'dd-MM-yyyy');

I came up with this (based on Anatoly answer):

import { parse, isValid, format } from 'date-fns';
import { enGB } from 'date-fns/locale';

function isValidDate(day, month, year) {
  const parsed = parse(`${day}/${month}/${year}`, 'P', new Date(), { locale: enGB })
  return isValid(parsed)
}

console.log(isValidDate('31', '04', '2021')); // invalid: april has only 30 days
console.log(isValidDate('30', '04', '2021')); // valid
Related