Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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);
- }
- }
Add Comment
Please, Sign In to add comment