React,Formik,Yup:验证数组的顺序

时间:2019-12-13 13:38:10

标签: reactjs formik yup

我用React,Formik和Yup创建了一个简单的表单。它包含数字列表。我想验证列表的顺序是递增的:

  • 1,2,3有效
  • 1,5,100有效
  • 3,1,2无效
  • 100,99,98无效

我检查了Yup文档,但是没有什么可以升序或降序的。到这里去的最好方法是什么?

import React, { useState, Fragment } from "react";
import ReactDOM from "react-dom";
import { Formik, FieldArray, Form, Field } from "formik";
import * as Yup from "yup";

function App() {
  const [values] = useState({
    someNumbers: [1, 2, 3]
  });

  const validationSchema = Yup.object().shape({
    // how can I check for the correct order here?
    someNumbers: Yup.array()
  });

  return (
    <div className="App">
      <Formik
        initialValues={values}
        onSubmit={values =>
          setTimeout(() => {
            alert(JSON.stringify(values, null, 2));
          }, 500)
        }
        validationSchema={validationSchema}
      >
        {formikProps => (
          <Form>
            <FieldArray
              name="listOfDates"
              render={({ move, swap, push, insert, unshift, pop }) => (
                <Fragment>
                  {formikProps.values.someNumbers.map((d, index) => (
                    <Field type="number" name={`someNumbers.${index}`} />
                  ))}
                </Fragment>
              )}
            />
            <div>
              <button type="submit">Submit</button>
            </div>
            <pre>{JSON.stringify(formikProps.errors, null, 2)}</pre>
            <pre>{JSON.stringify(formikProps.values, null, 2)}</pre>
          </Form>
        )}
      </Formik>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

这里的代码为codesandbox

1 个答案:

答案 0 :(得分:1)

我想我有点晚了。但这可以帮助您:

// Custom Validation
Yup.addMethod(Yup.array, 'sorted', function (message, parser = a => a) {
  return this.test('sorted', message, function (list) {
      return Boolean(
        list
          .map(parser)
          .reduce((valid, item) => valid && item >= valid && item)
      );
  });
});

然后您可以执行以下操作:

const arr1 = [1,2,3];
const validationSchema1 = Yup.array().sorted('Shame!');

const arr2 = [{id:1},{id:2},{id:3}];
const validationSchema2 = Yup.array().sorted('Shame!', a => a.id);

这里是一个示例:https://codesandbox.io/s/nameless-dust-fjxon