giulio giulio - 6 months ago 12
Java Question

How do you validate an Australian Business Number (ABN) format in Java?

I need to validate an Australian Business Number format before submitting it for verification to the server. There seems to be solutions for web/js but none written in Java. Note that I do not need to validate the existence of the ABN, just the format.

Answer

After some research I couldn't find a simple solution based on Java. So, I created my own, based on the information from clearwater.com.au

I have reprinted the rules in case the link disappears.

enter image description here

//A fully trimmed abn must be used.
public static boolean validABN(String abn) {
            boolean result = false;
            int[] weighting = {10, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19};
            int checksum = 0;

            if (isNumeric(abn)) {
                if (abn.length() == 11) {
                    for (int i = 0; i < abn.length(); i++) {
                        char c = abn.charAt(i);
                        int posValue = Integer.parseInt(String.valueOf(c));
                        // subtract 1 from first digit only
                        if (i == 0) {
                            posValue -= 1;
                        }
                        // calculate value with position weighting
                        int calculation = posValue * weighting[i];
                        checksum += calculation;
                    }

                    int remainder = checksum % 89;

                    if (remainder == 0) {
                        result = true;
                    }
                } 
            }
            return result;
        }