Skip to content

Instantly share code, notes, and snippets.

@dtelaroli
Created July 13, 2020 17:24
Show Gist options
  • Select an option

  • Save dtelaroli/bad4f4d3491cc9c2fc0d862fffe12916 to your computer and use it in GitHub Desktop.

Select an option

Save dtelaroli/bad4f4d3491cc9c2fc0d862fffe12916 to your computer and use it in GitHub Desktop.
Joi Validator validate cpf-cnpj field
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