Here's an example we can all try (and help me out). Validating that the input into a date field is a valid date using formik and yup. The problem is that stuff like "11" gets turned into a valid date:
Abbreviated prompt:
dateOfBirth: date().required().typeError('Invalid Date')
})
The dateOfBirth validation is incorrect because it accepts values like "11". What is the correct validation to ensure that a user has inputted a valid date?
GPTs first go:
****
dateOfBirth: date()
.required()
.typeError('Invalid Date')
.min(new Date(1900, 0, 1), 'Date must be after 1900')
.max(new Date(), 'Date cannot be in the future'),
In this example, the min method sets a minimum date of January 1, 1900, and the max method sets a maximum date of the current date. You can adjust the minimum and maximum dates as needed to fit your specific use case.
****
Me:
It still treats "11" as valid input
GPT second attempt:
*****
dateOfBirth: date()
.required()
.typeError('Invalid Date')
.test('valid-date', 'Invalid date', (value) => {
if (!value) {
return false;
}
const date = new Date(value);
return !isNaN(date.getTime());
}),
*****
Me:
The parameter 'value' passed into test is a date and not a string
GPT third attempt:
******
dateOfBirth: date()
.required()
.typeError('Invalid Date')
.test('valid-date', 'Invalid date', (value) => {
return value instanceof Date && value.isValid();
}),
******
Me:
There is no isValid function on Date objects
GPT fourth attempt:
********
dateOfBirth: date()
.required()
.typeError('Invalid Date')
.test('valid-date', 'Invalid date', (value) => {
return value instanceof Date && !isNaN(value.getTime());
}),
********
Me:
That still accepts 11 as a valid date.
GPT fifth attempt:
*********
dateOfBirth: string()
.required()
.test('valid-date', 'Invalid date', (value) => {
const dateRegex = /^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$/;
if (!dateRegex.test(value)) {
return false;
}
const date = new Date(value);
return date instanceof Date && !isNaN(date.getTime());
}),
********
Which may or may not be correct. That regex is bonkers and given the errors in the previous responses I don't trust it.