How to reuse the Yup validation schema + sonar scan shown more duplication on yup schema validation files it increase the duplication coverage

Viewed 1386

I am working with multiple forms . In some cases the forms having similar fields eg, name , phone number , account number etc.., . I am using formik as well . I have created schema file (schema.js) for each form . Inside that i have listed down all the schema validation and return that schema.

eg : schema.js

const schema = yup.object().shape({
 firmName: yup.string().label(Labels.FIRM).max(255)
});
export default schema;

If i have 10 forms which has firmName field all my schema.js file has above propert firmName. I am not sure how to separate it and reuse it . If anyone has faced and solved similar case please let me know the way. In the above way of coding got increasing the duplication percentage in sonar scan. Please help

2 Answers

I'm doing this way:

const password = {
  password: yup.string().required().min(8),
};
const setupPassword = {
  ...password,
  confirmPassword: yup
    .string()
    .defined(t('password.confirm.required'))
    .test('passwords-match', t('password.confirm.match'), function (value) {
      return this.parent.password === value;
    }),
  agreeToTerms: yup.boolean().test('is-true', value => value === true),
};

export const SchemaPasswordValidation = yup.object().shape({
  ...setupPassword,
});

while accepted answer might also work I think it should be mentioned that you can now use method "concat" to join two schemas:

const passwordSchema = yup.string().required().min(8);
const setupPassword = yup.object({ ...whatever you need here... }).concat(passwordSchema);
const schemaPasswordValidation = yup.object({ ...whatever you need here... }).concat(passwordSchema)

Which I believe is exactly what you want to do.

And just FYI if you have base schema and you want to "extend" it you can also do:

const baseSchema = yup.object({ ...base fields... });
const schema = baseSchema.shape({ ...specific fields... };

(but in your case concat is probably better since 'passwordSchema' is not base of these other two schemas)

Related