'joi v17.4.1, Validate only mentioned or required field , all other params should be options
I'm using joi v17.4.1,to validate post input body parameters , but i want to only put the required parameters in JOi Schema For example , for Registration i need only username, Email and Password to be mandatory all others parameters will be options . So i'm creating joi schema like :
const registerUserValidator = async (body) => {
const schema = Joi.object().keys({
username: Joi.string()
.alphanum()
.min(3)
.max(30)
.required(),
password: Joi.string()
.pattern(new RegExp('^[a-zA-Z0-9]{3,30}$')),
repeat_password: Joi.ref('password'),
email: Joi.string()
.email({ minDomainSegments: 2, tlds: { allow: ['com', 'net'] } })
})
There user can post :
{
"username":"myuserName",
"name":"Test Name",
"email":"[email protected]",
"phone":"00000000",
"password":"12345",
"repeat_password":"12345",
}
I'm getting error :
{
"messeage": "\"name\" is not allowed"
}
> Please help
Solution 1:[1]
just add other fields with Joi.allow() as shown below:
const registerUserValidator = async (body) => {
const schema = Joi.object().keys({
username: Joi.string()
.alphanum()
.min(3)
.max(30)
.required(),
password: Joi.string()
.pattern(new RegExp('^[a-zA-Z0-9]{3,30}$')),
repeat_password: Joi.ref('password'),
email: Joi.string()
.email({ minDomainSegments: 2, tlds: { allow: ['com', 'net'] } }),
//add this in your code
phone:Joi.allow(),
name:Joi.allow()
})
Solution 2:[2]
You can also ignore every other field with the options passed in like so:
const registerUserValidator = async (body) => {
const schema = Joi.object({
username: Joi.string()
.alphanum()
.min(3)
.max(30)
.required(),
password: Joi.string().pattern(
new RegExp("^[a-zA-Z0-9]{3,30}$")
),
repeat_password: Joi.ref("password"),
email: Joi.string().email({
minDomainSegments: 2,
tlds: { allow: ["com", "net"] },
}),
});
return schema.validate(body, {
abortEarly: false,
allowUnknown: true,
});
};
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 | Hemant Modi |
| Solution 2 | Karim Bakkali |
