0

I have array field name ... unknown field name , array field name get from database. They is same validation .How to validation with yup unknown field name ?

const schema=yup.object().schema({
nameField1:yup.required('required')
        .min(5, 'min 5 characters')
        .max(10, 'max 10 characters'),
nameField2:yup.required('required')
        .min(5, 'min 5 characters')
        .max(10, 'max 10 characters'),
....
nameUnknown:yup.required('required')
        .min(5, 'min 5 characters')
        .max(10, 'max 10 characters'),
})
TienDev
  • 5
  • 1
  • 1
    What do you mean, "unknown"? If you just mean it's dynamic and stored in a variable, say `fieldName`, then you can use computed property names: `[fieldName]: yup.required(...)` – Robin Zigmond Oct 20 '20 at 15:50
  • It mean . I don't know name of field . I just know array data and i will render array input. – TienDev Oct 20 '20 at 16:11
  • If there's genuinely no way for your code to get hold of the name, then there's no hope. But that seems hard to believe. I will assume you're capable of getting it from somewhere - perhaps an API request? The details will vary depending on the source of the data, which is why I can't give you a formal answer - but whenever you get it, you can use that name, when stored in a variable, into your yup schema in a way that's at least similar to what I showed above. If you can give more detail about your component and how it acquires the field name, I should be able to give a more detailed answer. – Robin Zigmond Oct 20 '20 at 16:45

1 Answers1

0

I had a similar problem when working with dynamic forms. Meaning the backend would send me an object which I would use as a 'blueprint' if you will to make the form. In that case what worked for me was to use the form library validation method (in formik it's validateField) I think. Now, I'm not that familiar with react-hook-form, but I think doing your validations in the template like here would solve your problem.