I have a validationSchema that displays an error if a user selects a date before a certain timeframe, however when the user receives the error through Yup it displays as below, this isnt quite what i would like as i need the user to understand the problem
However I would like the date to be formatted in a way that a user would understand, for instance just the date rather than the full time and milliseconds. My code for this is below,
const validationSchema = Yup.object({
contractOptionToExtend: Yup.number('Option to Extend').required().min(0),
originalEndDate: Yup.date().required().min(Yup.ref('startDate')),
startDate: contract.leadContract && contract.leadContract.startDate ? Yup.date().min(contract.leadContract.startDate) : Yup.date(),
ultimateEndDate: Yup.date().min(Yup.ref('currentEndDate')),
currentEndDate: Yup.date().min(Yup.ref('originalEndDate'))
});
const initialValues = {
contractOptionToExtend: contract && contract.contractOptionToExtendId || -1,
originalEndDate: contract && contract.originalEndDate,
startDate: contract && contract.startDate,
ultimateEndDate: contract && contract.ultimateEndDate,
currentEndDate: contract && contract.currentEndDate
};
And my component of the date picker
<DatePicker
margin="normal"
format="d MMM yyyy"
label="Original End Date"
value={values.originalEndDate}
onChange={handleOriginalEndDateChange}
onBlurCapture={change.bind(null, 'originalEndDate')}
required
id="originalEndDate"
name="originalEndDate"
autoOk={true}
error={touched.originalEndDate && Boolean(errors.originalEndDate)}
helperText={touched.originalEndDate ? errors.originalEndDate : ''}
/>
Using Our Transform import { date, object } from "yup"; const today = new Date(); const schema = object({ birthday: date(). transform(parseDateString). max(today), }); const isValid = schema. validateSync({ birthday: "2020-02-02", });
1) Use a Calendar control to allow the user to select the date. 2) Use a Validate rule to test the value entered by the user. 3) Use an Edit Validate rule to test the value entered by the user.
The second argument to min()
is the message you want displayed. You can pass a string, or a function that receives an object with the 'min' value as its argument. You can then format the value to your liking. For this example I provided an example of a formatDate()
function that returns a nice and short date string, but you can do whatever else you need to.
function formatDate(date) {
return new Date(date).toLocaleDateString()
}
Yup.date().min(
Yup.ref('originalEndDate'),
({ min }) => `Date needs to be before ${formatDate(min)}!!`,
)
More info in Yup's docs
As a side note, this is also the case with the other validation functions. You can always use a function for the error message.
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