6

I working with yup validation and trying to build a conditional validation object

Normally, I use Field in redux form to handle form input value and validation it with yup, but In another case, I use FieldArray to implement complicate condition, this is a code I use FieldArray:

 <form onSubmit={handleSubmit}>
      <FieldArray
          name="session"
          component={RenderSession}
        />
 </form>

this is component I bind in FieldsArray,

export const RenderSession = ({ fields }) => {return (
  {fields.map((member, index) => (
    <div key={index}>
      <Field
        name={`${member}.name`}
        validate={validateProps}
      />
    </div>
    <Button onClick={() => fields.push({})}>
      Add
    </Button>
  </Row>
</>

I want to check validations the value of the field name = {$ {member} .startTime} how to use yup Please give me a solution for using yup with FieldsArray or anything else. In the case of this impossible, teach me to have another way, Feel free to question, Thanks

3
  • give me 1 hope, Plzzz Commented Dec 31, 2018 at 2:13
  • Can you create demo to reproduce an issue? Commented Jan 2, 2019 at 10:48
  • May be you can use Yup.test('isValid', value => {// return true or false}) Commented Jan 5, 2019 at 6:36

1 Answer 1

6
+25

from Yup docs you can check the element of an array against its schema, IE:

array().of(object().shape({ num: number().max(4) }))

ref: https://github.com/jquense/yup#arrayoftype-schema-schema

or a more fitting example:

const schema = Yup.object().shape({
  friends: Yup.array()
    .of(
      Yup.object().shape({
        name: Yup.string()
          .min(4, 'too short')
          .required('Required'), // these constraints take precedence
        salary: Yup.string()
          .min(3, 'cmon')
          .required('Required'), // these constraints take precedence
      })
    )
    .required('Must have friends') // these constraints are shown if and only if inner constraints are satisfied
    .min(3, 'Minimum of 3 friends'),
});
Sign up to request clarification or add additional context in comments.

2 Comments

@MosèRaguzzini What if I want to pass dynamic min and max values?
Hi mate, it will look like: Yup.string().min(4, 'too short').max(8, 'too long')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.