Created
July 13, 2020 17:24
-
-
Save dtelaroli/bad4f4d3491cc9c2fc0d862fffe12916 to your computer and use it in GitHub Desktop.
Joi Validator validate cpf-cnpj field
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
| const { cpf, cnpj } = require('cpf-cnpj-validator'); | |
| const Joi = require("@hapi/joi"); | |
| const JoiDoc = Joi.extend((joi) => ({ | |
| base: joi.string(), | |
| type: "string", | |
| messages: { | |
| 'document.invalid': '"{{#label}}" is invalid' | |
| }, | |
| rules: { | |
| document: { | |
| method(options) { | |
| return this.$_addRule({ name: 'document', args: { options } }); | |
| }, | |
| validate(value, {prefs, error}, args) { | |
| if (!cpf.isValid(value) && !cnpj.isValid(value)) { | |
| return error('document.invalid'); | |
| } | |
| return value; | |
| } | |
| } | |
| } | |
| })); | |
| //Using | |
| JoiDoc.string().document(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment