VALIDATOR - Validação de Dados
O que é este Node?
O VALIDATOR é o node responsável por validar dados de entrada contra regras específicas para garantir que estão no formato correto antes de prosseguir no flow.
Por que este Node existe?
Validar dados manualmente é trabalhoso e propenso a erros. O VALIDATOR existe para:
- Garantir qualidade dos dados: Valida se dados estão no formato esperado (email, telefone, CPF, etc.)
- Evitar erros downstream: Impede que dados inválidos cheguem a sistemas externos
- Validação complexa: Suporta múltiplas regras simultâneas (required, min, max, pattern)
- Feedback imediato: Retorna erros específicos para cada regra violada
- Reduzir código: Elimina necessidade de validações manuais em cada step
Como funciona internamente?
Quando o VALIDATOR é executado, o sistema:
- Recebe os dados a serem validados (objeto ou valor simples)
- Processa cada regra definida no array de rules
- Valida required: Verifica se campo obrigatório está presente
- Valida tipo: Verifica formato (email, phone, cpf, number, etc.)
- Valida range: Verifica min/max para números e comprimento de strings
- Valida pattern: Testa regex customizado se fornecido
- Coleta erros: Armazena todas as violações encontradas
- Retorna resultado: Objeto com valid (true/false) e lista de erros
Código interno (ai-processing-executor.service.ts:651-780):
private async executeValidator(parameters: any, context: any): Promise<any> {
const { data, rules, customRules } = parameters;
this.logger.log(`✅ VALIDATOR - Validating data with ${rules?.length || 0} rules`);
if (data === undefined || data === null) {
throw new Error('Data is required for validation');
}
const validationResults: any[] = [];
const errors: string[] = [];
// Process validation rules
if (rules && Array.isArray(rules)) {
for (const rule of rules) {
const { field, type, required, min, max, pattern } = rule;
const value = field ? data[field] : data;
const result = {
field: field || 'root',
rule: type,
valid: true,
message: null as string | null
};
// Required validation
if (required && (value === undefined || value === null || value === '')) {
result.valid = false;
result.message = `Field ${field || 'data'} is required`;
errors.push(result.message);
}
// Type validation
if (value !== undefined && value !== null && value !== '') {
switch (type) {
case 'email':
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailPattern.test(value)) {
result.valid = false;
result.message = `Invalid email format: ${value}`;
errors.push(result.message);
}
break;
case 'phone':
const phonePattern = /^\(?[1-9]{2}\)?\s?9?\d{4}-?\d{4}$/;
if (!phonePattern.test(String(value).replace(/\s/g, ''))) {
result.valid = false;
result.message = `Invalid phone format: ${value}`;
errors.push(result.message);
}
break;
case 'cpf':
const cpfPattern = /^\d{3}\.?\d{3}\.?\d{3}-?\d{2}$/;
if (!cpfPattern.test(String(value))) {
result.valid = false;
result.message = `Invalid CPF format: ${value}`;
errors.push(result.message);
}
break;
case 'number':
if (isNaN(Number(value))) {
result.valid = false;
result.message = `Invalid number: ${value}`;
errors.push(result.message);
}
break;
}
}
// Min/Max validation for numbers and strings
if (value !== undefined && value !== null && min !== undefined) {
if (typeof value === 'number' && value < min) {
result.valid = false;
result.message = `Value ${value} is less than minimum ${min}`;
errors.push(result.message);
} else if (typeof value === 'string' && value.length < min) {
result.valid = false;
result.message = `Text length ${value.length} is less than minimum ${min}`;
errors.push(result.message);
}
}
if (value !== undefined && value !== null && max !== undefined) {
if (typeof value === 'number' && value > max) {
result.valid = false;
result.message = `Value ${value} is greater than maximum ${max}`;
errors.push(result.message);
} else if (typeof value === 'string' && value.length > max) {
result.valid = false;
result.message = `Text length ${value.length} is greater than maximum ${max}`;
errors.push(result.message);
}
}
// Pattern validation
if (value !== undefined && value !== null && pattern) {
const regex = new RegExp(pattern);
if (!regex.test(String(value))) {
result.valid = false;
result.message = `Value does not match pattern: ${value}`;
errors.push(result.message);
}
}
validationResults.push(result);
}
}
const isValid = errors.length === 0;
return {
success: true,
action: 'data_validated',
data: data,
rules: rules || [],
validation: {
valid: isValid,
errors: errors,
results: validationResults,
totalRules: validationResults.length,
passedRules: validationResults.filter(r => r.valid).length
},
timestamp: new Date().toISOString()
};
}
Quando você DEVE usar este Node?
Use VALIDATOR sempre que precisar garantir qualidade de dados:
Casos de uso
- Formulários de cadastro: Validar email, telefone, CPF antes de salvar no banco
- Integrações externas: Verificar dados antes de enviar para APIs
- Qualidade de leads: Filtrar leads com dados inválidos ou incompletos
- Compliance: Garantir que dados atendem requisitos legais (formato CPF/CNPJ)
- Prevenção de erros: Detectar problemas antes de processar pagamentos ou pedidos
Quando NÃO usar VALIDATOR
- Captura de dados: Use INPUT/NUMBER/EMAIL com validação inline
- Decisões de negócio: Use CONDITION para lógica de negócio
- Transformação: Use FORMATTER para reformatar dados
Parâmetros Detalhados
data (any, obrigatório)
O que é: Os dados a serem validados. Pode ser um valor simples (string/number) ou um objeto com múltiplos campos.
Exemplos:
- Valor simples:
"jose@email.com" - Objeto:
{"email": "jose@email.com", "phone": "(11) 99999-9999"}
Flow completo para testar data simples:
{
"name": "Teste VALIDATOR - Data Simples",
"nodes": [
{
"id": "start_1",
"type": "start",
"position": { "x": 100, "y": 100 },
"data": { "label": "Início" }
},
{
"id": "input_1",
"type": "input",
"position": { "x": 300, "y": 100 },
"data": {
"label": "Pedir Email",
"parameters": {
"message": "Digite seu email:",
"variable": "user_email"
}
}
},
{
"id": "validator_1",
"type": "validator",
"position": { "x": 500, "y": 100 },
"data": {
"label": "Validar Email",
"parameters": {
"data": "{{user_email}}",
"rules": [
{
"type": "email",
"required": true
}
]
}
}
},
{
"id": "message_1",
"type": "message",
"position": { "x": 700, "y": 100 },
"data": {
"label": "Resultado",
"parameters": {
"message": "Email validado: {{user_email}}"
}
}
},
{
"id": "end_1",
"type": "end",
"position": { "x": 900, "y": 100 },
"data": { "label": "Fim" }
}
],
"edges": [
{ "source": "start_1", "target": "input_1" },
{ "source": "input_1", "target": "validator_1" },
{ "source": "validator_1", "target": "message_1" },
{ "source": "message_1", "target": "end_1" }
]
}
Teste: Digite jose@teste.com - válido! Digite jose@ - inválido!
rules (array, obrigatório)
O que é: Array de regras de validação. Cada regra define um campo e suas validações.
Estrutura de cada rule:
{
"field": "nome_do_campo",
"type": "email|phone|cpf|cnpj|number|custom",
"required": true,
"min": 10,
"max": 100,
"pattern": "^[A-Z0-9]+$"
}
Flow completo para testar rules:
{
"name": "Teste VALIDATOR - Multiple Rules",
"nodes": [
{
"id": "start_1",
"type": "start",
"position": { "x": 100, "y": 100 },
"data": { "label": "Início" }
},
{
"id": "variable_1",
"type": "variable",
"position": { "x": 300, "y": 100 },
"data": {
"label": "Dados de Teste",
"parameters": {
"name": "user_data",
"value": {
"email": "jose@teste.com",
"phone": "(11) 99999-9999",
"age": 25
}
}
}
},
{
"id": "validator_1",
"type": "validator",
"position": { "x": 500, "y": 100 },
"data": {
"label": "Validar Todos",
"parameters": {
"data": "{{user_data}}",
"rules": [
{
"field": "email",
"type": "email",
"required": true
},
{
"field": "phone",
"type": "phone",
"required": true
},
{
"field": "age",
"type": "number",
"required": true,
"min": 18,
"max": 120
}
]
}
}
},
{
"id": "message_1",
"type": "message",
"position": { "x": 700, "y": 100 },
"data": {
"label": "Sucesso",
"parameters": {
"message": "Todos os dados válidos!"
}
}
},
{
"id": "end_1",
"type": "end",
"position": { "x": 900, "y": 100 },
"data": { "label": "Fim" }
}
],
"edges": [
{ "source": "start_1", "target": "variable_1" },
{ "source": "variable_1", "target": "validator_1" },
{ "source": "validator_1", "target": "message_1" },
{ "source": "message_1", "target": "end_1" }
]
}
customRules (object, opcional)
O que é: Regras customizadas adicionais definidas pelo usuário (funcionalidade futura/extensível).
Padrão: undefined (não implementado na versão atual)
Parâmetros
| Campo | Tipo | Obrigatório | Descrição |
|---|---|---|---|
| data | any | Sim | Dados a validar (valor simples ou objeto) |
| rules | array | Sim | Array de regras de validação |
| customRules | object | Não | Regras customizadas adicionais |
Estrutura de Rule
| Campo | Tipo | Obrigatório | Descrição |
|---|---|---|---|
| field | string | Não | Nome do campo (omitir para validar data diretamente) |
| type | string | Sim | Tipo: email, phone, cpf, cnpj, number, custom |
| required | boolean | Não | Campo obrigatório (padrão: false) |
| min | number | Não | Valor/comprimento mínimo |
| max | number | Não | Valor/comprimento máximo |
| pattern | string | Não | Regex customizado (usar com type: custom) |
Exemplo 1: Validação de Email Simples
Objetivo: Validar que usuário digitou um email válido
JSON para Importar
{
"name": "VALIDATOR - Email Simples",
"nodes": [
{
"id": "start_1",
"type": "start",
"position": { "x": 100, "y": 100 },
"data": { "label": "Início" }
},
{
"id": "input_1",
"type": "input",
"position": { "x": 300, "y": 100 },
"data": {
"label": "Pedir Email",
"parameters": {
"message": "Por favor, digite seu email:",
"variable": "email"
}
}
},
{
"id": "validator_1",
"type": "validator",
"position": { "x": 500, "y": 100 },
"data": {
"label": "Validar Email",
"parameters": {
"data": "{{email}}",
"rules": [
{
"type": "email",
"required": true
}
]
}
}
},
{
"id": "condition_1",
"type": "condition",
"position": { "x": 700, "y": 100 },
"data": {
"label": "Email Válido?",
"parameters": {
"condition": "{{validation.valid}} == true"
}
}
},
{
"id": "message_valid",
"type": "message",
"position": { "x": 900, "y": 50 },
"data": {
"label": "Email Válido",
"parameters": {
"message": "Email cadastrado com sucesso: {{email}}"
}
}
},
{
"id": "message_invalid",
"type": "message",
"position": { "x": 900, "y": 150 },
"data": {
"label": "Email Inválido",
"parameters": {
"message": "Email inválido! Por favor, verifique o formato."
}
}
},
{
"id": "end_valid",
"type": "end",
"position": { "x": 1100, "y": 50 },
"data": { "label": "Fim" }
},
{
"id": "end_invalid",
"type": "end",
"position": { "x": 1100, "y": 150 },
"data": { "label": "Fim" }
}
],
"edges": [
{ "source": "start_1", "target": "input_1" },
{ "source": "input_1", "target": "validator_1" },
{ "source": "validator_1", "target": "condition_1" },
{ "source": "condition_1", "target": "message_valid", "label": "true" },
{ "source": "condition_1", "target": "message_invalid", "label": "false" },
{ "source": "message_valid", "target": "end_valid" },
{ "source": "message_invalid", "target": "end_invalid" }
]
}
Saída esperada:
Sistema: Por favor, digite seu email:
Usuário: jose@teste.com
Sistema: Email cadastrado com sucesso: jose@teste.com
Ou, se inválido:
Sistema: Por favor, digite seu email:
Usuário: jose@
Sistema: Email inválido! Por favor, verifique o formato.
Exemplo 2: Validação de CPF/CNPJ
Objetivo: Validar documentos brasileiros (CPF ou CNPJ) com formatação flexível
JSON para Importar
{
"name": "VALIDATOR - CPF/CNPJ",
"nodes": [
{
"id": "start_1",
"type": "start",
"position": { "x": 100, "y": 100 },
"data": { "label": "Início" }
},
{
"id": "input_cpf",
"type": "input",
"position": { "x": 300, "y": 100 },
"data": {
"label": "Pedir CPF",
"parameters": {
"message": "Digite seu CPF (formato: 123.456.789-00):",
"variable": "cpf"
}
}
},
{
"id": "validator_1",
"type": "validator",
"position": { "x": 500, "y": 100 },
"data": {
"label": "Validar CPF",
"parameters": {
"data": "{{cpf}}",
"rules": [
{
"type": "cpf",
"required": true
}
]
}
}
},
{
"id": "condition_1",
"type": "condition",
"position": { "x": 700, "y": 100 },
"data": {
"label": "CPF Válido?",
"parameters": {
"condition": "{{validation.valid}} == true"
}
}
},
{
"id": "message_valid",
"type": "message",
"position": { "x": 900, "y": 50 },
"data": {
"label": "CPF OK",
"parameters": {
"message": "CPF validado: {{cpf}}"
}
}
},
{
"id": "message_invalid",
"type": "message",
"position": { "x": 900, "y": 150 },
"data": {
"label": "CPF Inválido",
"parameters": {
"message": "CPF inválido! Use formato: 123.456.789-00"
}
}
},
{
"id": "end_1",
"type": "end",
"position": { "x": 1100, "y": 100 },
"data": { "label": "Fim" }
}
],
"edges": [
{ "source": "start_1", "target": "input_cpf" },
{ "source": "input_cpf", "target": "validator_1" },
{ "source": "validator_1", "target": "condition_1" },
{ "source": "condition_1", "target": "message_valid", "label": "true" },
{ "source": "condition_1", "target": "message_invalid", "label": "false" },
{ "source": "message_valid", "target": "end_1" },
{ "source": "message_invalid", "target": "end_1" }
]
}
Saída esperada:
Sistema: Digite seu CPF (formato: 123.456.789-00):
Usuário: 123.456.789-00
Sistema: CPF validado: 123.456.789-00
Exemplo 3: Validação de Cartão de Crédito
Objetivo: Validar número de cartão de crédito usando pattern customizado
JSON para Importar
{
"name": "VALIDATOR - Cartão de Crédito",
"nodes": [
{
"id": "start_1",
"type": "start",
"position": { "x": 100, "y": 100 },
"data": { "label": "Início" }
},
{
"id": "input_cartao",
"type": "input",
"position": { "x": 300, "y": 100 },
"data": {
"label": "Número do Cartão",
"parameters": {
"message": "Digite o número do cartão (16 dígitos):",
"variable": "numero_cartao"
}
}
},
{
"id": "input_cvv",
"type": "input",
"position": { "x": 500, "y": 100 },
"data": {
"label": "CVV",
"parameters": {
"message": "Digite o CVV (3 dígitos):",
"variable": "cvv"
}
}
},
{
"id": "input_validade",
"type": "input",
"position": { "x": 700, "y": 100 },
"data": {
"label": "Validade",
"parameters": {
"message": "Digite a validade (MM/AA):",
"variable": "validade"
}
}
},
{
"id": "variable_cartao",
"type": "variable",
"position": { "x": 900, "y": 100 },
"data": {
"label": "Dados do Cartão",
"parameters": {
"name": "cartao",
"value": {
"numero": "{{numero_cartao}}",
"cvv": "{{cvv}}",
"validade": "{{validade}}"
}
}
}
},
{
"id": "validator_1",
"type": "validator",
"position": { "x": 1100, "y": 100 },
"data": {
"label": "Validar Cartão",
"parameters": {
"data": "{{cartao}}",
"rules": [
{
"field": "numero",
"type": "custom",
"required": true,
"pattern": "^\\d{16}$"
},
{
"field": "cvv",
"type": "custom",
"required": true,
"pattern": "^\\d{3}$"
},
{
"field": "validade",
"type": "custom",
"required": true,
"pattern": "^(0[1-9]|1[0-2])\\/\\d{2}$"
}
]
}
}
},
{
"id": "condition_valid",
"type": "condition",
"position": { "x": 1300, "y": 100 },
"data": {
"label": "Cartão Válido?",
"parameters": {
"condition": "{{validation.valid}} == true"
}
}
},
{
"id": "message_aprovado",
"type": "message",
"position": { "x": 1500, "y": 50 },
"data": {
"label": "Aprovado",
"parameters": {
"message": "Cartão validado! Processando pagamento..."
}
}
},
{
"id": "message_recusado",
"type": "message",
"position": { "x": 1500, "y": 150 },
"data": {
"label": "Recusado",
"parameters": {
"message": "Dados do cartão inválidos! Por favor, verifique."
}
}
},
{
"id": "end_1",
"type": "end",
"position": { "x": 1700, "y": 100 },
"data": { "label": "Fim" }
}
],
"edges": [
{ "source": "start_1", "target": "input_cartao" },
{ "source": "input_cartao", "target": "input_cvv" },
{ "source": "input_cvv", "target": "input_validade" },
{ "source": "input_validade", "target": "variable_cartao" },
{ "source": "variable_cartao", "target": "validator_1" },
{ "source": "validator_1", "target": "condition_valid" },
{ "source": "condition_valid", "target": "message_aprovado", "label": "true" },
{ "source": "condition_valid", "target": "message_recusado", "label": "false" },
{ "source": "message_aprovado", "target": "end_1" },
{ "source": "message_recusado", "target": "end_1" }
]
}
Saída esperada:
Sistema: Digite o número do cartão (16 dígitos):
Usuário: 1234567890123456
Sistema: Digite o CVV (3 dígitos):
Usuário: 123
Sistema: Digite a validade (MM/AA):
Usuário: 12/25
Sistema: Cartão validado! Processando pagamento...
Exemplo 4: Cadastro Completo com Validação
Objetivo: Validar múltiplos campos de um formulário com diferentes regras
JSON para Importar
{
"name": "VALIDATOR - Cadastro Completo",
"nodes": [
{
"id": "start_1",
"type": "start",
"position": { "x": 100, "y": 100 },
"data": { "label": "Início" }
},
{
"id": "message_intro",
"type": "message",
"position": { "x": 300, "y": 100 },
"data": {
"label": "Boas-vindas",
"parameters": {
"message": "Bem-vindo ao cadastro! Vamos coletar seus dados."
}
}
},
{
"id": "input_nome",
"type": "input",
"position": { "x": 500, "y": 100 },
"data": {
"label": "Nome",
"parameters": {
"message": "Qual seu nome completo?",
"variable": "nome"
}
}
},
{
"id": "input_email",
"type": "input",
"position": { "x": 700, "y": 100 },
"data": {
"label": "Email",
"parameters": {
"message": "Qual seu email?",
"variable": "email"
}
}
},
{
"id": "input_telefone",
"type": "input",
"position": { "x": 900, "y": 100 },
"data": {
"label": "Telefone",
"parameters": {
"message": "Qual seu telefone? (formato: (11) 99999-9999)",
"variable": "telefone"
}
}
},
{
"id": "input_idade",
"type": "number",
"position": { "x": 1100, "y": 100 },
"data": {
"label": "Idade",
"parameters": {
"message": "Qual sua idade?",
"variable": "idade"
}
}
},
{
"id": "variable_dados",
"type": "variable",
"position": { "x": 1300, "y": 100 },
"data": {
"label": "Agrupar Dados",
"parameters": {
"name": "cadastro",
"value": {
"nome": "{{nome}}",
"email": "{{email}}",
"telefone": "{{telefone}}",
"idade": "{{idade}}"
}
}
}
},
{
"id": "validator_1",
"type": "validator",
"position": { "x": 1500, "y": 100 },
"data": {
"label": "Validar Tudo",
"parameters": {
"data": "{{cadastro}}",
"rules": [
{
"field": "nome",
"type": "custom",
"required": true,
"min": 5,
"max": 100,
"pattern": "^[a-zA-ZÀ-ÿ\\s]+$"
},
{
"field": "email",
"type": "email",
"required": true
},
{
"field": "telefone",
"type": "phone",
"required": true
},
{
"field": "idade",
"type": "number",
"required": true,
"min": 18,
"max": 120
}
]
}
}
},
{
"id": "condition_valid",
"type": "condition",
"position": { "x": 1700, "y": 100 },
"data": {
"label": "Dados Válidos?",
"parameters": {
"condition": "{{validation.valid}} == true"
}
}
},
{
"id": "message_sucesso",
"type": "message",
"position": { "x": 1900, "y": 50 },
"data": {
"label": "Cadastro OK",
"parameters": {
"message": "Cadastro realizado com sucesso!\n\nNome: {{nome}}\nEmail: {{email}}\nTelefone: {{telefone}}\nIdade: {{idade}} anos\n\nObrigado!"
}
}
},
{
"id": "message_erro",
"type": "message",
"position": { "x": 1900, "y": 150 },
"data": {
"label": "Erro de Validação",
"parameters": {
"message": "Alguns dados estão inválidos. Por favor, corrija e tente novamente."
}
}
},
{
"id": "end_1",
"type": "end",
"position": { "x": 2100, "y": 100 },
"data": { "label": "Fim" }
}
],
"edges": [
{ "source": "start_1", "target": "message_intro" },
{ "source": "message_intro", "target": "input_nome" },
{ "source": "input_nome", "target": "input_email" },
{ "source": "input_email", "target": "input_telefone" },
{ "source": "input_telefone", "target": "input_idade" },
{ "source": "input_idade", "target": "variable_dados" },
{ "source": "variable_dados", "target": "validator_1" },
{ "source": "validator_1", "target": "condition_valid" },
{ "source": "condition_valid", "target": "message_sucesso", "label": "true" },
{ "source": "condition_valid", "target": "message_erro", "label": "false" },
{ "source": "message_sucesso", "target": "end_1" },
{ "source": "message_erro", "target": "end_1" }
]
}
Saída esperada (sucesso):
Sistema: Bem-vindo ao cadastro! Vamos coletar seus dados.
Sistema: Qual seu nome completo?
Usuário: José Roberto Silva
Sistema: Qual seu email?
Usuário: jose@empresa.com
Sistema: Qual seu telefone? (formato: (11) 99999-9999)
Usuário: (11) 98765-4321
Sistema: Qual sua idade?
Usuário: 35
Sistema: Cadastro realizado com sucesso!
Nome: José Roberto Silva
Email: jose@empresa.com
Telefone: (11) 98765-4321
Idade: 35 anos
Obrigado!
Resposta do Node
{
"success": true,
"action": "data_validated",
"data": {
"email": "jose@teste.com",
"phone": "(11) 99999-9999",
"age": 25
},
"rules": [
{
"field": "email",
"type": "email",
"required": true
},
{
"field": "phone",
"type": "phone",
"required": true
},
{
"field": "age",
"type": "number",
"required": true,
"min": 18,
"max": 120
}
],
"validation": {
"valid": true,
"errors": [],
"results": [
{
"field": "email",
"rule": "email",
"valid": true,
"message": null
},
{
"field": "phone",
"rule": "phone",
"valid": true,
"message": null
},
{
"field": "age",
"rule": "number",
"valid": true,
"message": null
}
],
"totalRules": 3,
"passedRules": 3
},
"timestamp": "2025-01-15T10:30:00.000Z"
}
Resposta com Erros
{
"success": true,
"action": "data_validated",
"data": {
"email": "jose@",
"phone": "123",
"age": 15
},
"rules": [...],
"validation": {
"valid": false,
"errors": [
"Invalid email format: jose@",
"Invalid phone format: 123",
"Value 15 is less than minimum 18"
],
"results": [
{
"field": "email",
"rule": "email",
"valid": false,
"message": "Invalid email format: jose@"
},
{
"field": "phone",
"rule": "phone",
"valid": false,
"message": "Invalid phone format: 123"
},
{
"field": "age",
"rule": "number",
"valid": false,
"message": "Value 15 is less than minimum 18"
}
],
"totalRules": 3,
"passedRules": 0
},
"timestamp": "2025-01-15T10:30:00.000Z"
}
Tipos de Validação Suportados
- Pattern:
/^[^\s@]+@[^\s@]+\.[^\s@]+$/ - Válidos:
jose@teste.com,user@example.com.br - Inválidos:
jose@,@teste.com,jose
Phone (Brasileiro)
- Pattern:
/^\(?[1-9]{2}\)?\s?9?\d{4}-?\d{4}$/ - Válidos:
(11) 99999-9999,11999999999,(11) 9999-9999 - Inválidos:
123,99999,(00) 99999-9999
CPF
- Pattern:
/^\d{3}\.?\d{3}\.?\d{3}-?\d{2}$/ - Válidos:
123.456.789-00,12345678900 - Inválidos:
123,12.345.678-9
Number
- Validação:
isNaN(Number(value)) - Válidos:
123,45.67,-10 - Inválidos:
abc,12abc,undefined
Custom (Pattern)
- Uso: Qualquer regex customizado
- Exemplos:
- CEP:
^\d{5}-?\d{3}$ - Placa:
^[A-Z]{3}-?\d{4}$ - Código:
^[A-Z0-9]{6,10}$
Boas Práticas
✅ SIM:
- Use VALIDATOR antes de enviar dados para APIs externas
- Combine múltiplas regras em um único validator para validação completa
- Use CONDITION após validator para tratar dados válidos/inválidos
- Defina min/max apropriados para prevenir inputs absurdos
- Use pattern para validações específicas do seu domínio
- Sempre defina required: true para campos obrigatórios
❌ NÃO:
- Não use VALIDATOR para lógica de negócio (use CONDITION)
- Não confie apenas em validação client-side (sempre valide no backend)
- Não ignore os erros retornados (sempre trate validation.errors)
- Não use validações muito complexas em um único pattern (quebre em múltiplas rules)
Dicas
💡 Múltiplas regras: Valide vários campos de uma vez passando objeto em data
💡 Feedback específico: Use validation.errors para mostrar mensagens detalhadas ao usuário
💡 Validação incremental: Valide campos importantes primeiro, depois campos secundários
💡 Pattern testing: Teste seus regex em https://regex101.com antes de usar
💡 Type + Pattern: Combine type predefinido com pattern customizado para validações mais rígidas
Próximo Node
→ FORMATTER - Formatar dados após validação → CALCULATOR - Calcular valores validados → CONDITION - Decidir fluxo baseado em validation.valid