CaioElias
CaioElias3mo ago

JS BLOCK

function validarCPF(cpfNumerico) { if (cpfNumerico.length === 11) { return cpfNumerico; } else { return null; } } var somenteNumerosCPF = last_utterance.replace(/\D/g, ''); var cpfFormatado = validarCPF(somenteNumerosCPF); The JavaScript block above is failing. What is the reason? It is not returning the cpfNumerico variable nor null, it's failing.
1 Reply
Tico | Voiceflow Assistant
The script never gets to the return inside validarCPF – it crashes on the line that tries to run ".replace()". Inside a Function (or the JS Code step’s sandbox) the variable last_utterance is not automatically in scope. Because it is undefined, the call
last_utterance.replace(/\D/g,'');
last_utterance.replace(/\D/g,'');
throws TypeError: replace is not a function and the whole block aborts, so nothing is returned. How to fix 1. Add last_utterance to the step’s input variables and read it from args.inputVars (Functions) or make sure the Code step is reached after the user has spoken so the variable exists.
export default async function main(args) {
const { last_utterance = '' } = args.inputVars; // ⬅️ bring the VF variable into scope
const somenteNumerosCPF = last_utterance.replace(/\D/g,'');

const cpfFormatado = somenteNumerosCPF.length === 11 ? somenteNumerosCPF : null;

return {
outputVars: { cpfFormatado }, // write the value back to VF
next: { path: 'success' }
};
}
export default async function main(args) {
const { last_utterance = '' } = args.inputVars; // ⬅️ bring the VF variable into scope
const somenteNumerosCPF = last_utterance.replace(/\D/g,'');

const cpfFormatado = somenteNumerosCPF.length === 11 ? somenteNumerosCPF : null;

return {
outputVars: { cpfFormatado }, // write the value back to VF
next: { path: 'success' }
};
}
2. (If you’re using the low-code Code step instead of a Function) wrap the access in a default value so the step won’t crash when last_utterance is still empty:
var somenteNumerosCPF = (last_utterance || '').replace(/\D/g,'');
var somenteNumerosCPF = (last_utterance || '').replace(/\D/g,'');
Either change prevents the runtime error, allowing the function to return the CPF or null as intended. Docs: https://docs.voiceflow.com

Did you find this page helpful?