Created
April 24, 2023 21:53
-
-
Save acaburaz/23533d235b387873170018244f8925d9 to your computer and use it in GitHub Desktop.
Swedish Orgnummer Validator C#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Linq; | |
using System.Text.RegularExpressions; | |
public bool ValidateOrgNumber(string value) | |
{ | |
// Check if the input has the correct format (6 digits followed by optional '-' and 4 more digits) | |
if (!Regex.IsMatch(value, @"^\d{6}-?\d{4}$")) return false; | |
// Remove any non-digit characters (e.g., '-') | |
value = Regex.Replace(value, @"\D", ""); | |
// Reverse the string and create pairs of digits and their positions (odd/even) | |
var digitPositionPairs = value.Reverse() | |
.Select((c, index) => (digit: c - '0', isEvenPosition: index % 2 == 1)); | |
// Apply the Luhn algorithm transformation to each digit based on its position | |
var transformedDigits = digitPositionPairs | |
.Select(pair => pair.isEvenPosition ? pair.digit * 2 : pair.digit); | |
// Subtract 9 from digits greater than 9 | |
var adjustedDigits = transformedDigits | |
.Select(digit => digit > 9 ? digit - 9 : digit); | |
// Calculate the checkSum using the adjusted digits | |
int checkSum = adjustedDigits.Sum(); | |
// Return true if the checkSum is a multiple of 10 | |
return checkSum % 10 == 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment