我需要一些现代的C#代码来检查澳大利亚商业号码(ABN)是否有效。
要求松散
验证号码的确切规则在abr.business.gov.au指定,为了简洁和清楚起见,这里省略了这些规则。规则不会随着时间而改变。
答案 0 :(得分:4)
这是基于Nick Harris's样本,但清理后使用现代C#习语
+--------------------+----------------------+------+-----+---------------------+-----------------------------+
| Field | Type | Null | Key | Default | Extra |
+--------------------+----------------------+------+-----+---------------------+-----------------------------+
| entity_id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| created_at | timestamp | NO | | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
| updated_at | timestamp | NO | | 0000-00-00 00:00:00 | |
| status | smallint(5) unsigned | NO | | 1 | |
| title | text | NO | | NULL | |
| author | text | NO | | NULL | |
| post_date | timestamp | NO | | 0000-00-00 00:00:00 | |
| summary | text | NO | | NULL | |
| content_html | text | NO | | NULL | |
| meta_description | text | YES | | NULL | |
| meta_title | text | YES | | NULL | |
| meta_keywords | text | YES | | NULL | |
| store_ids | text | NO | | NULL | |
| category_ids | text | NO | | NULL | |
| tag_ids | text | NO | | NULL | |
| cms_identifier | varchar(255) | YES | UNI | NULL | |
| customer_group_ids | text | YES | | NULL | |
| publish_date | timestamp | YES | | NULL | |
| use_summary | smallint(6) | YES | | 1 | |
| root_template | varchar(255) | YES | | NULL | |
| layout_update_xml | text | YES | | NULL | |
+--------------------+----------------------+------+-----+---------------------+-----------------------------+
奖励xUnit测试让您的技术领导感到高兴......
/// <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;
}
答案 1 :(得分:1)
Python
def isValidABN(ABN = None):
if(ABN == None): return False
ABN = ABN.replace(" ","")
weight = [10,1,3,5,7,9,11,13,15,17,19]
weightedSum = 0
if(len(ABN) != 11): return False
if(ABN.isnumeric() == False): return False
i = 0
for number in ABN:
weightedSum += int(number) * weight[i]
i += 1
weightedSum -= 10 #This is the same as subtracting 1 from the first digit.
result = weightedSum % 89 == 0
return result
答案 2 :(得分:0)
试试这个:
var abn = "51 824 753 556";
var weighting = new [] { 10, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19 };
var isValid =
abn
.Where(x => char.IsDigit(x))
.Select((x, n) => (x - '0') - (n == 0 ? 1 : 0))
.Zip(weighting, (d, w) => d * w)
.Sum() % 89 == 0;
IsValid
输入ABN的true
或false
是否有效。
答案 3 :(得分:0)
我的验证ABN和ACN的JavaScript版本
ABN:
function isValidABN(num) {
const weights = new Array(10, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19);
// Convert to string and remove all white space
num = num.toString().replace(/\s/g, "");
// Split it to number array
num = num.split('').map(n => parseInt(n));
// Subtract 1 from the first (left-most) digit of the ABN to give a new 11 digit number
num[0] = num[0] - 1;
// Multiply each of the digits in this new number by a "weighting factor" based on its position as shown in the table below
num = num.map((n, i) => n * weights[i]);
// Sum the resulting 11 products
let total = num.reduce((acc, n) => {
return acc + n;
}, 0);
// Divide the sum total by 89, noting the remainder
if(total % 89 === 0) {
return true;
} else {
return false;
}
}
ACN:
function isValidACN(num) {
const weights = new Array(8, 7, 6, 5, 4, 3, 2, 1);
// Convert to string and remove all white space
num = num.toString().replace(/\s/g, "");
// Split it to number array
num = num.split('').map(n => parseInt(n));
// Set the check digit and remove it
let checkDigit = num.pop();
// Apply weighting to digits 1 to 8.
num = num.map((n, i) => n * weights[i]);
// Sum the products
let total = num.reduce((acc, n) => {
return acc + n;
}, 0);
// Divide by 10 to obtain remainder
let calculatedCheckDigit = (10 - (total % 10)) % 10;
// calculatedCheckDigit should match check digit
if(calculatedCheckDigit === checkDigit) {
return true;
} else {
return false;
}
}
答案 4 :(得分:0)
完整代码 http://www.expertsuggestion.com/2019/06/abn-number-validation-with-javascript.html
我的ABN号码验证(带有掩盖GooD运气的ABN号码格式)
// html部分
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!------ Include the above in your HEAD tag ---------->
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.js"></script>
<div class="container">
<div class="row">
<div>
<form id="register_form" class="forms-sample" method="post" action="register" enctype="multipart/form-data">
<div class="form-group">
<label >ABN Number</label>
<input id="contact_abn_no" type="text" name="abn_no" class="form-control" value="" placeholder="ABN Number">
<span class="text-danger" style="font-size:12px;display:none;">{{ $errors->first('abn_no') }}</span>
</div>
<br/>
<div>
<button style="margin-top:0px;" type="submit" class="btn btn-primary btn-lg btn-block btn-block_top_margin btnsubload">Submit</button>
</div>
</form>
</div>
</div>
</div>
//jquery part
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.10/jquery.mask.js"></script>
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(function() {
$("#contact_abn_no").mask("00 000 000 000", {
onChange: function () {
console.log($('#contact_abn_no').val());
}
});
});
$(function(){
$("#register_form").validate({
rules: {
"abn_no": {
checkAbn : true,
required: true
}
},
messages: {
"abn_no": {
required: "Please Enter ABN Number"
}
},
highlight: function (element, errorClass, validClass) {
$("#loading").css("visibility", "hidden");
return false;
$("#loading").css("visibility", "visible");
},
errorElement: 'span',
submitHandler: function (form) {
form.submit();
}
});
$.validator.addMethod("checkAbn", function(value, element) {
var abn_val = $("#contact_abn_no").val()
if (abn_val.trim() != '') {
var weights = [10, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19];
if (abn_val.length == 14) {
//remove spaces from string
abn_val = abn_val.replace(/\s+/g, '');
// strip anything other than digits
abn_val = abn_val.replace("/[^\d]/", "");
// check length is 11 digits
if (abn_val.length == 11) {
// apply ato check method
var sum = 0;
for (var i = 0; i < 11; i++) {
var digit = abn_val[i] - (i ? 0 : 1);
var sum = sum + (weights[i] * digit);
}
return ((sum % 89) == 0);
} else {
return false;
}
}
} else {
return true;
}
// return true;
}, "ABN number not vailid.");
})
</script>