Question:
How to do Yup validation in form with TypeScript?

Problem

I have a form that can create or edit an object. Each attribute is required so you cannot create/save an object without a valid A and B. I'm using yup and TypeScript latest version.


interface Exemple{

  A: number;

  B: number;

}


To do that I have two number inputs that can return a number or NaN if empty or invalid number. I made a validation function that I can then add to yup with addMethod :


export function validateExemple(): Yup.ObjectSchema<Exemple> {

  return Yup.object<Exemple>().shape({

    A: Yup.number()

      .transform((value) => (isNaN(value) ? undefined : value))

      .required()

      .max(20)

      .min(-20),

    B: Yup.number()

      .transform((value) => (isNaN(value) ? undefined : value))

      .required()

      .max(30)

      .min(-30),

  });

}


I need to convert Nan value to undefined to avoid an exception on min/max. This function work as intended despite the type error :


Type 'ObjectSchema<{ A: number | undefined; B: number | undefined; }, Exemple, { A: undefined; B: undefined; }, "">' is not assignable to type 'ObjectSchema<Exemple, AnyObject, any, "">'.


My problem is that I don't want to change the base type to number | undefined because unless I'm not in the form A and B cannot be undefined. I thought about using two different types (Exemple and ExempleForm) but that would duplicate all the types used in forms in my application.


I'm looking for a way to write a validation function that does the same thing, with this type and without the error.


Is there a solution to what I'm asking?


Solution

You can try like this :


export function validateExemple(): Yup.ObjectSchema<Exemple> {

  const numberSchema = Yup.number()

                          .nullable()

                          .transform((value) => (isNaN(value) ? null : value));

                                return Yup.object<Exemple>().shape({

                                   A: numberSchema.required().max(20).min(-20),

                                   B: numberSchema.required().max(30).min(-30),

                                });

  }


As you can see here, you can use nullable method in Yup instead of undefined.


Suggested blogs:

>Why Typescript does not allow a union type in an array?

>Narrow SomeType vs SomeType[]

>Create a function that convert a dynamic Json to a formula in Typescript

>How to destroy a custom object within the use Effect hook in TypeScript?

>How to type the values of an object into a spreadsheet in TypeScript?

>Type key of record in a self-referential manner in TypeScript?

>How to get the last cell with data for a given column in TypeScript?

>Ignore requests by interceptors based on request content in TypeScript?

>Create data with Typescript Sequelize model without passing in an id?

>How to delete duplicate names from Array in Typescript?


Nisha Patel

Nisha Patel

Submit
0 Answers