gpt4 book ai didi

c# - 验证 ABN(澳大利亚商业编号)

转载 作者:太空宇宙 更新时间:2023-11-03 21:09:16 24 4
gpt4 key购买 nike

我需要一些现代 C# 代码来检查澳大利亚商业号码 (ABN) 是否有效。

松散的要求是

  • ABN 已由用户输入
  • 允许在任何位置使用空格以使数字可读
  • 如果包含除数字和空格之外的任何其他字符 - 即使包含合法的数字序列,验证也应该失败
  • 此检查是调用 ABN search webservice 的前奏这将节省输入明显错误的电话

验证数字的确切规则在 abr.business.gov.au 中指定。为了简洁和清楚起见,此处省略。规则不会随时间改变。

最佳答案

这是基于Nick Harris's示例,但经过清理以使用现代 C# 习语

/// <summary>
/// http://stackoverflow.com/questions/38781377
/// 1. Subtract 1 from the first (left) digit to give a new eleven digit number
/// 2. Multiply each of the digits in this new number by its weighting factor
/// 3. Sum the resulting 11 products
/// 4. Divide the total by 89, noting the remainder
/// 5. If the remainder is zero the number is valid
/// </summary>
public bool IsValidAbn(string abn)
{
abn = abn?.Replace(" ", ""); // strip spaces

int[] weight = { 10, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19 };
int weightedSum = 0;

//0. ABN must be 11 digits long
if (string.IsNullOrEmpty(abn) || !Regex.IsMatch(abn, @"^\d{11}$"))
{
return false;
}

//Rules: 1,2,3
for (int i = 0; i < weight.Length; i++)
{
weightedSum += (int.Parse(abn[i].ToString()) - (i == 0 ? 1 : 0)) * weight[i];
}

//Rules: 4,5
return weightedSum % 89 == 0;
}

额外的 xUnit 测试让您的技术主管开心...

[Theory]
[InlineData("33 102 417 032", true)]
[InlineData("29002589460", true)]
[InlineData("33 102 417 032asdfsf", false)]
[InlineData("444", false)]
[InlineData(null, false)]
public void IsValidAbn(string abn, bool expectedValidity)
{
var sut = GetSystemUnderTest();
Assert.True(sut.IsValidAbn(abn) == expectedValidity);
}

关于c# - 验证 ABN(澳大利亚商业编号),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38781377/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com