I would like to centralize forms validation. I created a file: src/schemas/schemas.js.
On this file I'm placing all forms validations, for example:
export const schemaRegister = yup.object().shape({
username: yup.string().required("Username is required").matches(/^[0-9a-z]+$/),
password: yup.string().required("Password is required").min(8).otherValidations...,
passwordConfirmation: yup.string()
.required("Password confirmation is required")
.oneOf([yup.ref("password"), null], "Passwords must match")
});
export const schemaLogin = yup.object().shape({
username: yup.string().required("Username is required"),
password: yup.string().required("Password is required").min(8).otherValidations...,
});
OTHER SCHEMAS
I have two doubts:
Is it ok to have all forms validations schemas in one single file (src/schemas/schemas.js)?
As you can see, in both schemas, I'm repeating
password: yup.string().required("Password is required").min(8).otherValidations...
is there a way to avoid to repeat the code? Because I have other forms with some fields that have a complicated validation, so I would like to not repeat it
You can avoid repetition. Lets say you want to use schemaLogin in schemaRegister. You can merge these schemas using .shape like this:
const schemaRegister = schemaLogin.shape({
passwordConfirmation: yup.string()
.required("Password confirmation is required")
.oneOf([yup.ref("password"), null], "Passwords must match")
});