How to add and remove validation field to yup.validationSchema
const validationSchema = yup.object().shape({
password: yup
.string()
.label('Password')
.required()
.min(2, 'Seems a bit short...')
.max(10, 'We prefer insecure system, try a shorter password.'),
});
for adding validation you can use concat, checkout the documentation here:
https://github.com/jquense/yup#mixedconcatschema-schema-schema
You can define your basic validation and add additional validations later on. Be carefully that you are just concat of the same type.
Example:
const requiredSchema = Yup.string().required();
const min2Schema = Yup.string().min(2, 'Seems a bit short...');
const passwordSchema = Yup.string()
.label('Password')
.max(10, 'We prefer insecure system, try a shorter password.')
.concat(requiredSchema)
.concat(min2Schema);
All that schemas are .string() schemas. You can just concat an object with objects, string with strings, number with numbers etc.
For making conditional validations, you can just add an inline-condition:
let isRequired = true;
const nameAndPasswordSchemaObject = Yup.object().shape({
name: nameSchema.concat( isRequired ? requiredSchema : null ),
password: passwordSchema,
});
The same goes for yup-objects:
const emailSchemaObject = Yup.object({
email: Yup.string().concat(requiredSchema)
});
const validationSchema = nameAndPasswordSchemaObject.concat(emailSchemaObject);
I hope that helps.
About removing schemas I couldn't see anything in the documentation (but never needed it)
For someone that looking for another approach, like dependent on value inside the schema itself
import * as yup from 'yup';
export const Schema = yup
.object()
.shape({
name: yup.string().lowercase().required(),
phone: yup.number().default(0).required(),
})
.when((values, schema) => {
if (values.name === 'john') {
return schema.shape({
isHungry: yup.boolean().required(),
food: yup.string().default('Pizza'),
});
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With