I have been using Joi library for validation user inputs like this.
const Joi = require('joi');
const schema = Joi.object({
username: Joi.string()
.alphanum()
.min(3)
.max(30)
.required()
});
const validationResult = await schema.validateAsync({ username: 'a' }, { abortEarly: false, warnings: true });
This works fine, the problem is later in code I would want to use this validation again.
But the warning messages are still in the local context.
And if I input he { username: ‘ba’} the error message will still display that min length of “a” needs to be 3.
Do you know how can I use the schema object again, and strip the local warnings context.
1
Validation context in Joi can carry over between validations when reusing the same schema instance. Try these two approaches and see if it solves the problem:
Create fresh schema clone for each validation:
const baseSchema = Joi.object({
username: Joi.string()
.alphanum()
.min(3)
.max(30)
.required()
});
// Use schema.clone() for each validation
const validationResult1 = await baseSchema.clone().validateAsync({ username: 'a' });
const validationResult2 = await baseSchema.clone().validateAsync({ username: 'ba' });
Create a validation function that always uses a fresh schema:
const validateUsername = async (data) => {
const schema = Joi.object({
username: Joi.string()
.alphanum()
.min(3)
.max(30)
.required()
});
return await schema.validateAsync(data, { abortEarly: false, warnings: true });
};
// Use it multiple times
try {
await validateUsername({ username: 'a' });
await validateUsername({ username: 'ba' });
} catch (err) {
console.error(err);
}
The second approach is generally preferred because:
- It ensures a clean validation context every time
- It encapsulates the validation logic in a reusable function
- It’s more explicit about the validation being performed
- It prevents any potential memory leaks from storing validation state
I hope this helps
2