5

I have a Relay app and it shares a GraphQL schema with the server. For every mutation, it queries the server, and the server returns back with the error message about what field value is invalid. But given that schema is present on the client, too, is it possible to do client-side validation against this schema?

rishat
  • 8,206
  • 4
  • 44
  • 69

1 Answers1

0

A pragmatic solution could be by using the Yup and Formik symbiose and then manual create the yup schema object around your inputType which is shared on both front- and backend.

While you're not validating 1-1 against the schema provided by the relay compiler, it is still a pragmatic way for validating on the client side.

JavaScript solution: Create a validation schema based on the custom input type, and pass the validationSchema to Formik:

const Schema = object().shape({
  coolOrWhat: boolean()
});

return (
  <Formik
    initialValues={{
      coolOrWhat: true
    }}
    validationSchema={Schema}
    ...
  >
  {/* form inputs here */}
  </Formik>
)

TypeScript solution: create the object for validation, infer the type and annotate this object when instantiating the formik component:

const Schema = object({
 foo: string()
});

export type SchemaType = InferType<typeof Schema>;

type Props = {
 onConfirm: (value: SchemaType) => void;
 onCancel: () => void;
};

<Formik<SchemaType>
 validationSchema={Schema} 
 ...>
 ...
</>
mikemols
  • 824
  • 10
  • 17