您如何在Java中验证澳大利亚商业号码(ABN)格式?

时间:2016-02-21 23:20:25

标签: java validation

我需要先验证澳大利亚商业号码格式,然后再将其提交给服务器进行验证。似乎有web/js的解决方案,但没有用Java编写。请注意,我不需要验证ABN的存在,只需格式化。

3 个答案:

答案 0 :(得分:3)

经过一番研究,我找不到一个基于Java的简单解决方案。所以,我根据clearwater.com.au

中的信息创建了自己的

如果链接消失,我已重新打印规则。

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;
}

答案 1 :(得分:2)

试试这个。

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;
}

答案 2 :(得分:1)

这是一个基于java8的验证ABN号码的解决方案

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);
}