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'
Date-fns provides you with date validation helpers with the isValid() function that checks if a given date is valid. By default, date-fns returns a Boolean variable true if the date parsed is indeed a valid date or false if the date string parsed is not a valid date.
parse() method is employed to parse the date string. The method inputs the date as an argument and returns the milliseconds. Moreover, you can use regular expressions to validate a date as well. The expression checks that the user entered the date by following the “mm/dd/yy” format.
Method #1 : Using strptime() In this, the function, strptime usually used for conversion of string date to datetime object, is used as when it doesn't match the format or date, raises the ValueError, and hence can be used to compute for validity.
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With