0
votes

I'm trying to write a react native application using Formik + Yup for schema validation and I'm having some trouble trying to extract the constants passed in max validation.

Let's imagine the following schema:

const message = string()
  .max(30)
  .default(1)

In my React Native component, let's say a custom TextInput, I wanted to get the constants 30 so that I can pass it to the maxLength prop:

<TextInput maxLength={max} {...otherProps} />

(of course the schema is simplified)

Does anybody know if it's feasible? How I can dig into a yup schema to access that constant and pass it to my TextInput?

2
You want to deliver 30 when the letter "TextInput" is 30?hong developer
I want my TextInput to be limited to 30, I want to extract the 30 constant from the Yup schema :) so that I define it in only one placemfrachet

2 Answers

1
votes

You could pass a function to validationSchema prop, so basically your yup schema would be,

const validationSchema = value => Yup.object().shape({
   name : Yup.string().max(values.max).default(1)
  });

In <Formik/> component level render method,

const { max } = this.state;

<Formik
 validationSchema={()=> validationSchema({max}) 
 ...>
  <TextInput maxLength={max} {...otherProps} />
</Formik>
1
votes

Call schema.describe(). This will return a description of the schema including a "tests" array. One of the items in the test array will be have a name "max", and also a "params" object containing a "max" value.

const description = schema.describe();
const maxTest = description.tests.find(t => t.name === 'max');
const maxValue = maxTest && maxTest.params ? maxTest.params.max : undefined;

You should be able to get access to most of the validations in the same way, however there's not currently a way to learn whether transformations like 'lowercase' and 'strip' are applied.

You will of course have to expose the schema for each field to do the above. Alternatively you can call describe() on the parent object schema and interrogate interrogate the "fields" property, then do something similar to the above.