189
rated 0 times
[
195]
[
6]
/ answers: 1 / hits: 6133
/ 3 Years ago, wed, march 31, 2021, 12:00:00
I am working in React JS . I need to implement validation using Formik and Yup for an array field as show below. Validation condition is such a way that the input time should not be equal to or between the existing time(The time that had already entered . Eg: if I enter 14.05 it should show an error, because the input time is already between 14.00 (start) and 03.00 (end) ). How can I validate the fields I think concept is clear. If there any doubts please do ask.
// API values
//home_delivery_monday_times: Array(3)
//0: {start: "09:00", end: "11:00"}
//1: {start: "14:00", end: "03:00 "}
//2: {start: "11:30", end: "13:00 "}
//length: 3
<Formik
initialValues={formData}
enableReinitialize={true}
validationSchema={yup.object({
settings: yup.object({
home_delivery_monday_times:
yup.array().of(yup.object({ start: yup.string() })).test("is-valid", "The value shouldn't equal or between the existing", function (value) {
return (
// Validating conditions
)
})
})
})}
onSubmit={(values: any, { setSubmitting }) => {
console.log("values", values)
}}
>
{formik =>
.....}
{formik?.values?.settings?.home_delivery_monday_times?.map((item: any, index: any) => (
<>
{index != 0 &&
<div className="p-col-12 p-sm-2 p-md-2" />
}
<div className="p-col-5 p-sm-4 p-md-4">
<label>Start</label>
<Field as={Calendar} value={item?.start ? new Date(`01-01-2000 ${item?.start}:00`) : ''} onSelect={(e: any) => { formik?.setFieldValue(`settings.home_delivery_monday_times.${index}.start`, moment(e?.value).format("HH:mm")) }} name={`settings.home_delivery_monday_times.${index}.start`} readOnlyInput={true} timeOnly />
<div className='p-col-12'>
<ErrorMessage name={`settings.home_delivery_monday_times.${index}.start`} component={FormErrorMsg} />
</div>
</div>
<div className="p-col-5 p-sm-4 p-md-4">
<label>End</label> <br />
<Field as={Calendar} value={item?.end ? new Date(`01-01-2000 ${item?.end?.trim()}:00`) : ''} onSelect={(e: any) => { formik?.setFieldValue(`settings.home_delivery_monday_times.${index}.end`, moment(e?.value).format("HH:mm")) }} name={`settings.home_delivery_monday_times.${index}.end`} readOnlyInput={true} timeOnly />
</div>
<div className="p-col-1 p-sm-2 p-md-2">
{index != 0 &&
<FiXCircle name="name" color="red" size="20px" onClick={() => formik?.values?.settings?.home_delivery_monday_times?.splice(index, 1)} />
}
</div>
</>
))}
More From » reactjs