'How to format Yup date() to brazilian format?
I'm wanting to use yup to validate an input, that is being used as Birthday. By first I added the simple .date() function to the yup shaped object, but it won't accept Brazilian dates, as the format is same as European (dd/MM/YYYY), how do I proceed?
Solution 1:[1]
Use .transform() to parse your value with a function passing the following parameters:
valueas current Date parsed by yup.originalValueas the original inputted value (e.g. "01/01/2022").
yup.date().transform((value, originalValue) => {
// Do your parsing structure
return newValue
})
Remember that your newValue must be a Date object since you want to validate a yup.date() type in your form.
You can use this example as solution for you to parse your value to "dd/MM/YYYY" format:
// Input: '10/12/2022'
// yup.object({ [...]
birthday: yup.date().transform((value, originalValue) => {
// originalValue = "10/12/2022"
try {
let date = originalValue.split('/')
// date = ["10", "12", "2022"] <- day, month and year respectively
if (date.length === 3) {
let newDate = `${date[2]}-${date[1]}-${date[0]}`
return new Date(newDate)
}
return null
} catch (e) {
return null
}
}),
// [...] })
// Expected Output: '2022-10-12T00:00:00.000Z'
See yup docs about parsing values using
.transform(): Yup Schema Basics - Parsing: Transforms
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Daniel Mendes Neto |
