'Hapi/Joi Cannot apply rules to empty ruleset or the last rule added does not support rule properties
I am trying to display a custom message when users didn't put a password during login. This worked fine when I don't have a custom message for the password:
const ValidationSchemas = Joi.object({
name: Joi.string().min(6).required().messages({
"string.empty":"Display name cannot be empty",
"string.min":"Min 6 characteers"
}).optional(),
email: Joi.string().min(6).required().email().message("Must be a valid email address"),
password:Joi.string().min(6).required()
})
But the moment I tried to have a custom message for the empty password field, I got an error stating - Cannot apply rules to empty ruleset or the last rule added does not support rule properties
Here is the code that I am trying to have a custom message for the password:
const ValidationSchemas = Joi.object({
name: Joi.string().min(6).required().messages({
"string.empty":"Display name cannot be empty",
"string.min":"Min 6 characteers"
}).optional(),
email: Joi.string().min(6).required().email().message("Must be a valid email address"),
password:Joi.string().min(6).required().message("Password is required!")
})
How do I have a custom message for the password? many thanks in advance and greatly appreciate any help. thanks
Solution 1:[1]
Try this:
const ValidationSchemas = Joi.object({
name: Joi.string()
.min(6)
.required()
.messages({
'string.empty': 'Display name cannot be empty',
'string.min': 'Min 6 characteers',
})
.optional(),
email: Joi.string().min(6).required().email().message('Must be a valid email address'),
password: Joi.string().required().min(6).message('Password is required!'),
});
Solution 2:[2]
I had this same issue, i later found out that using message()
will terminate the current ruleset and cannot be followed by another rule option.
So instead of using message()
, i used this: messages({ 'any.only': 'GENERAL_MESSAGE_HERE' })
Hence, in your case, you should change your code to this:
const ValidationSchemas = Joi.object({
name: Joi.string()
.min(6)
.required()
.messages({
'string.empty': 'Display name cannot be empty',
'string.min': 'Min 6 characteers',
})
.optional(),
email: Joi.string().min(6).required().email().messages({
'any.only': 'Must be a valid email address',
}),
password: Joi.string()
.min(6)
.required()
.messages({ 'any.only': 'Password is required!' }),
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Cokiledelante |
Solution 2 | Israel Obanijesu |