skip to Main Content

I’m using Yup validation in a React Typescript application. Based on the validation schema, how can I determine if a particular field is required? (I’m creating a custom text field component, and I want to dynamically add a required property if the field is required in the schema.)

Right now, I have:

import * as yup from 'yup';

const schema = yup.object().shape({
  name: yup.string().required('Required'),
  email: yup.string(),
});
const isNameRequired = schema.fields['name'].spec?.presence === 'required';

The problem is – I’m getting the following Typescript error on spec:

Property 'spec' does not exist on type 'Reference<unknown> | ISchema<string, AnyObject, any, any>'.
  Property 'spec' does not exist on type 'Reference<unknown>'.ts(2339)

2

Answers


  1. Chosen as BEST ANSWER

    I ended up using a solution similar to this answer, but then simply cast a few of the variables as any (with an added /* eslint-disable @typescript-eslint/no-explicit-any */ at the top of the file). No matter what I tried casting to the "proper" way, it always ended up with another error, so I just decided it's not worth the headache, and that this should cause absolutely no issues, so I've proceeded using the following code with a clear conscience:

    /* eslint-disable @typescript-eslint/no-explicit-any */
    import * as yup from 'yup';
    
    const schema = yup.object().shape({
       name: yup.string().required('Required'),
       email: yup.string(),
    });
    
    const isFieldRequired = (fieldName: string): boolean => {
      const field = schema.describe().fields[fieldName] as any;
      return field.tests.some((item: any) => item.name === 'required') ?? false;
    };
    

  2. You can use something like this .describe()

    const schema = yup.object().shape({
       name: yup.string().required('Required'),
       email: yup.string(),
    });
       
    
      function isFieldRequired(field) {
        return (
          schema
            .describe()
            .fields[field].tests.findIndex(({ name }) => name === "required") >= 0
        );
      }
    
      console.log(isFieldRequired("name")); // returns true
      console.log(isFieldRequired("email")); // returns false
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search