angryITguy
angryITguy

Reputation: 9561

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.

Upvotes: 4

Views: 2620

Answers (3)

angryITguy
angryITguy

Reputation: 9561

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

static final int[] weighting = {10, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19};
// A fully trimmed ABN must be used.
public static boolean validABN(String abn) {
    if (isNumeric(abn)) {
        if (abn.length() == 11) {
            int checksum = 0;
            for (int i = 0; i < abn.length(); i++) {
                int posValue = Character.digit(abn.charAt(i), 10);
                // subtract 1 from first digit only
                if (i == 0) {
                    posValue--;
                }
                // calculate value with position weighting
                checksum += posValue * weighting[i];
            }
            return checksum % 89 == 0;
        } 
    }
    return false;
}

Upvotes: 5

Joker
Joker

Reputation: 55

Here is a java8 based solution for validating ABN number

private static boolean isValidAbnFormat(final String abn) {
    if(NumberUtils.isDigits(abn) && abn.length() != 11) {
        return false;
    }
    final int[] weights = {10, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19};
    //split abn number string by digits to get int array
    int [] abnDigits =  Stream.of(abn.split("\\B")).mapToInt(Integer::parseInt).toArray();
    //reduce by applying weight[index] * abnDigits[index] (NOTE: substract 1 for the first digit in abn number)
    int sum = IntStream.range( 0, weights.length )
            .reduce(0, (total, idx) -> total + weights[idx] * (idx == 0 ? abnDigits[idx] - 1 : abnDigits[idx]));
    return (sum % 89 == 0);
}

Upvotes: 1

user4910279
user4910279

Reputation:

Try this.

static boolean validateABN(String abn) {
    int[] weights = {10, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19};
    abn = abn.replaceAll("\\D", "");
    if (abn.length() == 11) {
         int sum = 0;
         for (int i = 0; i < abn.length(); ++i) {
             int digit = abn.charAt(i) - '0' - (i == 0 ? 1 : 0);
             sum += weights[i] * digit;
         }
        return sum % 89 ==0;
    } 
    return false;
}

Upvotes: 3

Related Questions