Skip to content

Instantly share code, notes, and snippets.

@cristobal
Last active July 10, 2020 11:13
Show Gist options
  • Save cristobal/1170460 to your computer and use it in GitHub Desktop.
Save cristobal/1170460 to your computer and use it in GitHub Desktop.
Validate Norwegian Organization Number
<?php
/**
* Validate orgnr
* Validates an string number according to the brreg spec
* https://www.brreg.no/om-oss/oppgavene-vare/alle-registrene-vare/om-enhetsregisteret/organisasjonsnummeret/
*
* Test case: https://repl.it/repls/TechnicalForcefulBsddaemon
*
* @param <string> $value
*/
function validate_orgnr($value) {
if (!preg_match("/^\d{9}$/", $value, $matches)) {
throw new \Exception("Value must be a sequence of 9 numbers (value: {$value})");
}
$numbers = array_map(
function ($value) { return intval($value); },
str_split($matches[0])
);
$weights = array( 3, 2, 7, 6, 5, 4, 3, 2 );
$products = array_map(
function ($weight, $index) use($numbers) { return $numbers[$index] * $weight; },
$weights,
array_keys($weights)
);
$sum = array_reduce(
$products,
function ($acc, $product) { return $acc + $product; },
0
);
$mod11 = 11;
$rem = $sum % $mod11;
$cn = $rem == 0
? 0
: $mod11 - $rem;
if ($cn >= 10) {
return false;
}
return $cn === $numbers[8];
}
/**
* Validate orgnr
* Validates an string number according to the brreg spec
* https://www.brreg.no/om-oss/oppgavene-vare/alle-registrene-vare/om-enhetsregisteret/organisasjonsnummeret/
*
* Test case https://repl.it/@cristobal1/HappyVengefulDiscussion
*
* @param {string} value
*/
function validate_orgnr (value) {
const pattern = /^\d{9}$/
if (!pattern.test(value)) {
throw new Error(`Value must be a sequence of 9 numbers (value: ${value})`)
}
const numbers = String(value).split('').map(value => Number(value))
const weights = [ 3, 2, 7, 6, 5, 4, 3, 2 ]
const products = weights.map((value, index) => numbers[index] * value)
const sum = products.reduce((acc, product) => acc + product, 0)
const mod11 = 11
const rem = sum % mod11
const cn = rem === 0
? 0
: mod11 - rem
if (cn >= 10) {
return false
}
return cn === numbers[8]
}
@cristobal
Copy link
Author

Also seems like the nor-id-num (C#) project does a check whether the first digit in the organzation number is an 8 or 9, still that is not a part of the BBREG spec.

@davidstrompremium
Copy link

davidstrompremium commented Jul 10, 2020 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment