30

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'

Rafael de Carvalho
  • 501
  • 1
  • 5
  • 10

3 Answers3

43

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');
Anatoly
  • 20,799
  • 3
  • 28
  • 42
4

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
cancerbero
  • 6,799
  • 1
  • 32
  • 24
0

I'm phasing a similar problem and I think this also solves it. I prefer this solution as the parsing is a bit more explicit than the locale object.

import { parse, isValid, format } from "date-fns";

const getFormmatedDate = (date) => {
  const parsed = parse(date, "dd/MM/yyyy", new Date());
  if (isValid(parsed)) {
    return format(parsed, "dd-MM-yyyy");
  }
  return null;
};

console.log(getFormmatedDate("31/04/1989")); // invalid: april has only 30 days
console.log(getFormmatedDate("30/04/1989"));

yoty66
  • 390
  • 2
  • 12