Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yup validation with FieldsArray, ReactJS, redux-from

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

like image 1000
Kiên Trần Trung Avatar asked Dec 27 '18 08:12

Kiên Trần Trung


1 Answers

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'),
});
like image 52
Mosè Raguzzini Avatar answered Sep 18 '22 03:09

Mosè Raguzzini