Skip to content

Commit 4dfc92d

Browse files
committed
Update README.md
1 parent 1150e15 commit 4dfc92d

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

README.md

+49
Original file line numberDiff line numberDiff line change
@@ -3728,6 +3728,55 @@ console.log(hashPwd); //ef5225a03e4f9cc953ab3c4dd41f5c4db7dc2e5b
37283728
<b><a href="#">↥ back to top</a></b>
37293729
</div>
37303730

3731+
## Q. ***How to Validate Data using joi Module in Node.js?***
3732+
3733+
Joi module is a popular module for data validation. This module validates the data based on schemas. There are various functions like `optional(), required(), min(), max(), etc which make it easy to use and a user-friendly module for validating the data.
3734+
3735+
```js
3736+
const Joi = require("joi");
3737+
3738+
//User-defined function to validate the user
3739+
function validateUser(user) {
3740+
3741+
const JoiSchema = Joi.object({
3742+
3743+
username: Joi.string().min(5).max(30).required(),
3744+
3745+
email: Joi.string().email().min(5).max(50).optional(),
3746+
3747+
date_of_birth: Joi.date().optional(),
3748+
3749+
account_status: Joi.string()
3750+
.valid("activated")
3751+
.valid("unactivated")
3752+
.optional(),
3753+
}).options({ abortEarly: false });
3754+
3755+
return JoiSchema.validate(user);
3756+
}
3757+
3758+
const user = {
3759+
username: "Deepak Lucky",
3760+
3761+
date_of_birth: "2000-07-07",
3762+
account_status: "activated",
3763+
};
3764+
3765+
let response = validateUser(user);
3766+
3767+
if (response.error) {
3768+
console.log(response.error.details);
3769+
} else {
3770+
console.log("Validated Data");
3771+
}
3772+
```
3773+
3774+
**&#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/schema-validation-using-joi-s2nhzs)**
3775+
3776+
<div align="right">
3777+
<b><a href="#">↥ back to top</a></b>
3778+
</div>
3779+
37313780
#### Q. ***Is it possible to use "Class" in Node.js?***
37323781
#### Q. ***Explain Error Handling approaches in Node.js?***
37333782
#### Q. ***How would you handle errors for async code in Node.js?***

0 commit comments

Comments
 (0)