'How to reuse the Yup validation schema + sonar scan shown more duplication on yup schema validation files it increase the duplication coverage
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
Solution 1:[1]
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Miroslav Gregor |
