Skip to content

Instantly share code, notes, and snippets.

@airtonix
Last active February 29, 2024 03:30
Show Gist options
  • Select an option

  • Save airtonix/7129b0ed825a929bac8120efa6e9466f to your computer and use it in GitHub Desktop.

Select an option

Save airtonix/7129b0ed825a929bac8120efa6e9466f to your computer and use it in GitHub Desktop.
Validate Australian Business Number
/**
* Checks ABN for validity using the published ABN checksum algorithm.
* @author Guy Carpenter
* @license http://www.clearwater.com.au/code None
* @param {String|Number} value abn to validate
* @return {Boolean} Is ABN Valid
*/
function validateABN (value) {
var weights = [10, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19],
abn = value.replace(/[^\d]/g, ''),
result = false;
// check length is 11 digits
if (abn.length === 11) {
// apply ato check method
var sum = 0,
weight;
for (var index = 0; index <= weights.length - 1; index++) {
weight = weights[index];
digit = abn[index] - (index ? 0 : 1);
sum += weight * digit;
}
result = sum % 89 === 0;
}
return result;
}
@teebu
Copy link

teebu commented Mar 29, 2023

If your ABN is anything spaced like 51 824 753 556 format, the replacer function needs a 'g' flag, or use the new replaceAll.

abn = value.replace(/[^\d]/g, '');

sample ABNs

@airtonix
Copy link
Author

If your ABN is anything spaced like 51 824 753 556 format, the replacer function needs a 'g' flag, or use the new replaceAll.

abn = value.replace(/[^\d]/g, '');

sample ABNs

👍

@teebu
Copy link

teebu commented Mar 30, 2023

I would also use proper declarations, let and the digit variable is missing declaration.

function validateAustralianABN(value) {

    const weights = [10, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19];
    let abn = value?.toString().replace(/[^\d]/g, '');
    let result = false;

    // check length is 11 digits
    if (abn?.length === 11) {

        // apply ato check method
        let sum = 0,
            weight,
            digit;

        for (let index = 0; index <= weights.length - 1; index++) {
            weight = weights[index];
            digit = abn[index] - (index ? 0 : 1);
            sum += weight * digit;
        }

        result = sum % 89 === 0;
    }

    return result;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment