If you build workflows for Chilean businesses (Shopify stores, forms, invoicing), you’ll run into the RUT, Chile’s tax ID. Customers type it in many ways (12.345.678-5, 123456785, 12345678-5), and a wrong RUT usually breaks invoicing or shipping later in the flow.
Here’s the Code node I use to normalize it, validate the check digit (modulo 11) and return it formatted.
Code node, mode “Run Once for Each Item”:
const input = String($json.rut || '');
const clean = input.toUpperCase().replace(/[^0-9K]/g, '');
let valid = false;
let formatted = null;
if (clean.length >= 2) {
const body = clean.slice(0, -1);
const dv = clean.slice(-1);
if (/^\d+$/.test(body)) {
let sum = 0, mul = 2;
for (let i = body.length - 1; i >= 0; i--) {
sum += Number(body[i]) * mul;
mul = mul === 7 ? 2 : mul + 1;
}
const res = 11 - (sum % 11);
const expected = res === 11 ? '0' : res === 10 ? 'K' : String(res);
valid = dv === expected;
formatted = body.replace(/\B(?=(\d{3})+(?!\d))/g, '.') + '-' + dv;
}
}
return { json: { ...$json, rut_clean: clean, rut_valid: valid, rut_formatted: formatted } };
Then add an IF node on rut_valid to route invalid records to a notification or a review sheet.
A few notes:
- Store
rut_cleanin your database and userut_formattedonly for display. This avoids duplicates of the same RUT in different formats. - The check digit can be K, so keep the value as a string, never as a number.
- A valid check digit doesn’t mean the RUT exists. For companies, you can confirm the business name and activity through the SII’s public lookup.
Hope it saves someone some time.