Created
March 15, 2021 09:48
-
-
Save navsqi/5f176a0bf5695678c85711d5a968c993 to your computer and use it in GitHub Desktop.
Validasi dengan Joi di Node.JS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Full docs: https://joi.dev/api/?v=17.4.0 | |
| const Joi = require('joi'); | |
| try { | |
| const schema = Joi.object().keys({ | |
| name: Joi.string().min(2).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 {#limit}`, | |
| 'any.required': `"username" is a required field`, | |
| }), | |
| email: Joi.string().email().required().messages({ | |
| 'string.base': `"email" should be a type of 'text'`, | |
| 'string.empty': `"email" cannot be an empty field`, | |
| 'string.min': `"email" should have a minimum length of {#limit}`, | |
| 'string.email': `"email" should invalid email`, | |
| 'any.required': `"email" is a required field`, | |
| }), | |
| phoneNumber: Joi.string().min(7).pattern(/^\d+$/).messages({ | |
| 'string.pattern.base': 'Should be numeric', | |
| }), | |
| password: Joi.string().min(3).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 {#limit}`, | |
| 'any.required': `"username" is a required field`, | |
| }), | |
| }); | |
| // req.body example: | |
| // { | |
| // "name": "Nauval", | |
| // "email": "nauval@mail.com", | |
| // "phoneNumber": "08123123123", | |
| // "password": "password" | |
| // } | |
| const result = await schema.validate(req.body, { abortEarly: false }); | |
| if (result.error) throw result.error.details; | |
| // ## Without async | |
| // const result = schema.validate(req.body, { abortEarly: false }); | |
| // if (result.error){ | |
| // return res.status(400).json({ | |
| // status: 'fail', | |
| // message: err, | |
| // }); | |
| // }; | |
| }catch (err) { | |
| res.status(400).json({ | |
| status: 'fail', | |
| message: err, | |
| }); | |
| } | |
| // Full docs: https://joi.dev/api/?v=17.4.0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment