Last active
April 25, 2019 08:22
-
-
Save munkiepus/60496fc2e44f9c5f55e6dbf7a2034303 to your computer and use it in GitHub Desktop.
Unique Learner Number (ULN) Validation in PHP
This file contains 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
<?php | |
/** | |
* @method ulnValidation | |
* | |
* Checks if a ULN number is in the correct format, 10 digits including a 1 digit checksum | |
* | |
* @link https://assets.publishing.service.gov.uk/government/uploads/system/uploads/attachment_data/file/795483/WSLP02_ULN_Validation_v3.pdf | |
* | |
* 1. Take the first 9 digits of the entered ULN. | |
* 2. Sum 10 × first digit + 9 x second digit + 8 x third digit + 7 x fourth digit + 6 x fifth digit | |
* + 5 x sixth digit + 4 x seventh digit + 3 x eighth digit + 2 × ninth digit | |
* 3. Divide this number by 11 and find the remainder (modulo function). | |
* 4. Subtract the remainder from 10. If this number matches the | |
* tenth digit from the entered ULN, the ULN format is valid. | |
* NOTE: the earlier versions of the gov document are wrong and it can be 0 | |
* | |
* @param int $uln | |
* | |
* @return bool | |
*/ | |
function ulnValidation($uln) | |
{ | |
// uln must only contain a number | |
if (!is_numeric($uln)){ | |
echo "not numeric $uln"; | |
return false; | |
} | |
// uln must only be 10 digits | |
if (10 != strlen(trim($uln))){ | |
echo "not 10 digits " . strlen(trim($uln)); | |
return false; | |
} | |
// uln must be positive whole number | |
if (intval($uln) < 1) { | |
echo "not positive number: " . intval($uln); | |
return false; | |
} | |
// uln must only be a whole number | |
if ($uln != round($uln)) { | |
echo "not whole number: " . round($uln); | |
return false; | |
} | |
// calculate the checksum | |
$firstNine = str_split(substr(trim($uln), 0, 9)); | |
$givenChecksum = substr(trim($uln), -1); | |
$total = 0; | |
for ($i = 0; $i<9; $i++){ | |
$multiplier = 10-$i; | |
$digit = intval($firstNine[$i]); | |
$total += $multiplier * $digit; | |
} | |
$mod = $total % 11; | |
$calcChecksum = 10 - $mod; | |
if ($givenChecksum != $calcChecksum){ | |
echo "checksum not valid $givenChecksum != $calcChecksum"; | |
return false; | |
} | |
return true; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment