最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to perform validation of a array field using formik and yup validation - Stack Overflow

programmeradmin3浏览0评论

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`} ponent={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>
                                                                                </>
    
                                                                            ))}

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`} ponent={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>
                                                                                </>
    
                                                                            ))}

Share Improve this question edited Apr 29, 2021 at 13:43 Happy bean asked Mar 31, 2021 at 5:32 Happy beanHappy bean 893 silver badges16 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

EDIT I advice making use of the moment library then you can use the code below:

import * as Yup from "yup";
import { Formik, Form, Field, FieldArray, ErrorMessage } from "formik";
import moment from "moment";

export default function App() {
  const isValid = (timeSlots) => {
    if (!timeSlots) return;

    // pare each slot to every other slot
    for (let i = 0; i < timeSlots.length; i++) {
      const slot1 = timeSlots[i];

      if (!slot1.start || !slot1.end) continue;

      const start1 = moment(slot1.start, "HH:mm");
      const end1 = moment(slot1.end, "HH:mm");

      for (let j = 0; j < timeSlots.length; j++) {
        // prevent parision of slot with itself
        if (i === j) continue;

        const slot2 = timeSlots[j];

        if (!slot2.start || !slot2.end) continue;
        const start2 = moment(slot2.start, "HH:mm");
        const end2 = moment(slot2.end, "HH:mm");

        if (
          start2.isBetween(start1, end1, undefined, "[]") ||
          end2.isBetween(start1, end1, undefined, "[]")
        ) {
          return `Overlapping time in slot ${j + 1}`;
        }
      }
    }
    // All time slots are are valid
    return "";
  };

  const handleSubmit = (values) => {
    console.log(values.mondayTimes);
  };

  return (
    <div className="container m-3">
      <Formik
        initialValues={{ mondayTimes: [{ start: "", end: "" }] }}
        onSubmit={handleSubmit}
        validationSchema={Yup.object().shape({
          mondayTimes: Yup.array()
            .of(
              Yup.object().shape({
                start: Yup.string().test("startTest", "Invalid Time", function (
                  value
                ) {
                  if (!value) return true;
                  return moment(value, "HH:mm").isValid();
                }),
                end: Yup.string().test("endTest", "Invalid Time", function (
                  value
                ) {
                  if (!value) return true;
                  if (!moment(value, "HH:mm").isValid()) {
                    return this.createError({ message: "Invalid Time" });
                  }

                  if (
                    moment(this.parent.start, "HH:mm").isSameOrAfter(
                      moment(this.parent.end, "HH:mm")
                    )
                  ) {
                    return this.createError({
                      message: "End time must be after start time"
                    });
                  }

                  return true;
                })
              })
            )
            .test("timesTest", "Error", function (value) {
              const message = isValid(value);
              return !message;
            })
        })}
        render={({ values, errors }) => (
          <Form>
            <FieldArray
              name="mondayTimes"
              render={(arrayHelpers) => (
                <div className="">
                  {values.mondayTimes.map((time, index) => (
                    <div className="row" key={index}>
                      <div className="col-5">
                        <div className="mb-3">
                          <label htmlFor="" className="form-label">
                            Start
                          </label>
                          <Field
                            className="form-control"
                            name={`mondayTimes.${index}.start`}
                          />
                          <ErrorMessage
                            className="form-text text-danger"
                            name={`mondayTimes.${index}.start`}
                          />
                        </div>
                      </div>
                      <div className="col-5">
                        <div className="mb-3">
                          <label htmlFor="" className="form-label">
                            End
                          </label>
                          <Field
                            className="form-control"
                            name={`mondayTimes.${index}.end`}
                          />
                          <ErrorMessage
                            className="form-text text-danger"
                            name={`mondayTimes.${index}.end`}
                          />
                        </div>
                      </div>

                      <div className="col-2 mt-4">
                        <button
                          className="btn btn-sm btn-danger m-2"
                          type="button"
                          onClick={() => arrayHelpers.remove(index)}
                        >
                          -
                        </button>
                      </div>
                    </div>
                  ))}

                  {isValid(values.mondayTimes)}

                  <button
                    className="btn btn-sm btn-primary m-2"
                    type="button"
                    onClick={() =>
                      arrayHelpers.insert(values.mondayTimes.length, {
                        start: "",
                        end: ""
                      })
                    }
                  >
                    +
                  </button>
                  <div>
                    <button className="btn btn btn-primary m-2" type="submit">
                      Submit
                    </button>
                  </div>
                </div>
              )}
            />
          </Form>
        )}
      />
    </div>
  );
}

Here is the codesandbox for you to try out

Although this post is quite old, it helped me out tremendously as a starting point for my own availability editing ponent.

To answer the question, finding if two intervals overlap is quite easy.

const t1 = [1,3]
const t2 = [2,5]

If we have two intervals like the above where each number represents an hour we can use the formula below to determine if they overlap:

const isOverlapping = Math.max(1,2) <= Math.min(3,5)

In plain terms, this equation says: An interval overlaps if the end time of the first interval happens after the start time of the next interval.

credit @baeldung

Now, to implement this in code we need to pare all intervals with each other use the above formula for parison.

credit @baeldung

Since @Rishabh Singh provided the answer of the Naive approach. I will provide a revised version that makes some of the below improvements:

  1. Replaces moment.js with the smaller, more modern date-fns library
  2. Replaces the Naive parison O(n^2) with the faster Sweep-Line Approach O(n*log(n))
  3. Adds support for multiple days of week
  4. Adds formik validation for when start/end times are not in a valid hh:mm format
  5. Adds formik validation for when time slots are not in ascending order

Here is the codesandbox link

发布评论

评论列表(0)

  1. 暂无评论