I have two users customer
and manager
. manager
has some extra fields in its schema. So for that i have created two joi schema objects:
- validating common schema (for customer and manager) and
- validating some extra fields for manager.
For the manager
validation i have to validate both the joi schema objects.
const commonSchema = Joi.object({
name: Joi.string().min(3).max(255).required(),
email: Joi.string().email().required(),
password: Joi.string().min(3).max(15).required(),
...
}).options({ allowUnknown: true });
const managerSchema = Joi.object({
contactNumber: Joi.string()
.length(10)
.pattern(/^[0-9] $/)
.required(),
creditCardNum: Joi.string().length(16).required(),
isApproved: Joi.boolean().default(false),
...
}).options({ allowUnknown: true });
const { errorOne } = commonSchema.validate(manager);
const { errorTwo } = managerSchema.validate(manager);
This works but if there another way of validating both the schemas for manager
and only commonSchema for customer
without using options.({ allowUnknown: true })
. Because i don't want to allow all unknown fields.
CodePudding user response:
a simple & easy solution will be to define the common fields as fields and not as joi object
.
please notice that in my code the ...
means spread operator.
const commonSchemaFields = {
name: Joi.string().min(3).max(255).required(),
email: Joi.string().email().required(),
password: Joi.string().min(3).max(15).required(),
};
const managerSchemaFields = {
...commonSchemaFields,
contactNumber: Joi.string()
.length(10)
.pattern(/^[0-9] $/)
.required(),
creditCardNum: Joi.string().length(16).required(),
isApproved: Joi.boolean().default(false),
};
const commonSchema = Joi.object({...commonSchemaFields}).options({ allowUnknown: true });
const managerSchema = Joi.object({...managerSchemaFields}).options({ allowUnknown: true })
const { errorOne } = commonSchema.validate(manager);
const { errorTwo } = managerSchema.validate(manager);