Reputation: 135
I was trying to set some validations with some custom messages in Joi. So, for example, I have discovered that when a string must have at least 3 characters we can use "string.min" key and associate this to a custom message. Example:
username: Joi.string().alphanum().min(3).max(16).required().messages({
"string.base": `Username should be a type of 'text'.`,
"string.empty": `Username cannot be an empty field.`,
"string.min": `Username should have a minimum length of 3.`,
"any.required": `Username is a required field.`,
}),
Now here is my question:
Question
// Code for question
repeat_password: Joi.ref("password").messages({
"string.questionHere": "Passwords must match each other...",
}),
What method (questionHere
) name need to set to repeat_password
to be able to notify the user that passwords must match? I don't even know if Join.ref("something")
accept .messages({...})
...
If someone could please show me some help in the Joi docs, I haven't find anything yet by there...
Upvotes: 3
Views: 2260
Reputation: 298
What you are trying to find here is the error type
. It can be found in the error object that the joi validate
function returns. eg: error.details[0].type
will give you what you are looking for.
Regarding your second question, Join.ref("something")
doesn't accept .messages({...})
. Here you can use valid
in conjunction with ref
.
eg:
const Joi = require('joi');
const schema = Joi.object({
username: Joi.string().alphanum().min(3).max(16).required().messages({
"string.base": `Username should be a type of 'text'.`,
"string.empty": `Username cannot be an empty field.`,
"string.min": `Username should have a minimum length of 3.`,
"any.required": `Username is a required field.`,
}),
password: Joi.string().required(),
password_repeat: Joi.any().valid(Joi.ref('password')).required().messages({
"any.only" : "Password must match"
})
});
const result = schema.validate({ username: 'abc', password: 'pass', password_repeat: 'pass1'});
// In this example result.error.details[0].type is "any.only"
Upvotes: 12