csharp NIP,REGON,PESEL Validator

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp NIP,REGON,PESEL Validator相关的知识,希望对你有一定的参考价值。

void Main()
{
	string nip = "1220781342";

	Console.WriteLine(Validator.IsValidNIP(nip) ? "NIP is valid" : "NIP is not valid");
		
	string regon = "730295378";
	
	Console.WriteLine(Validator.IsValidREGON(regon) ? "REGON is valid" : "REGON is not valid");

	string pesel = "93111698132";
	
	Console.WriteLine(Validator.IsValidPESEL(pesel) ? "PESEL is valid" : "PESEL is not valid");

}

public class Validator
{
	private static byte[] ToByteArray(string input) => input
		.ToCharArray()
		.Select(c => byte.Parse(c.ToString()))
		.ToArray();

	private static int ControlSum(byte[] numbers, byte[] weights) => numbers
		.Take(numbers.Length - 1)
		.Select((number, index) => new { number, index })
		.Sum(n => n.number * weights[n.index]);


	private static bool IsValid(string input, byte[] weights, Func<int, int> control)
	{
		var numbers = ToByteArray(input);

		bool result = false;

		if (input.Length == weights.Length + 1)
		{
			int controlSum = ControlSum(numbers, weights);
			
			int controlNum = control(controlSum);

			if (controlNum == 10)
			{
				controlNum = 0;
			}

			result = controlNum == numbers.Last();
		}

		return result;
	}

	public static bool IsValidREGON(string input)
	{
		byte[] weights = null;

		switch (input.Length)
		{
			case 7: weights = new byte[] { 2, 3, 4, 5, 6, 7 };
				break;

			case 9: weights = new byte[] { 8, 9, 2, 3, 4, 5, 6, 7 };
				break;

			case 14: weights = new byte[] { 2, 4, 8, 5, 0, 9, 7, 3, 6, 1, 2, 4, 8 };
				break;
				
			default: return false;
		}
	
		return IsValid(input, weights, controlSum => controlSum % 11);

	}

	public static bool IsValidPESEL(string input)
	{		
		byte[] weights = { 1, 3, 7, 9, 1, 3, 7, 9, 1, 3 };
		
		return IsValid(input, weights, controlSum => 10 - controlSum % 10);
	}

	public static bool IsValidNIP(string input)
	{
		byte[] weights = { 6, 5, 7, 2, 3, 4, 5, 6, 7 };
		
		return IsValid(input, weights, controlSum => controlSum % 11);

	}
}

以上是关于csharp NIP,REGON,PESEL Validator的主要内容,如果未能解决你的问题,请参考以下文章

检查 PESEL 仅为 11 位数字 - ORA-04073: 列列表无效

php 验证PESEL

csharp 使用LINQ检查列表中的项是否具有其属性之一的特定值,第二种方式使用“out”修饰符来返回va

从表中选择 2 个最大的 NIP

在使用codeigniter并从curl获取数据时在ajax中添加href

nodejs之爬虫