Created
July 31, 2018 09:06
-
-
Save theotherdy/9fd6662abf356a866876713f069103da to your computer and use it in GitHub Desktop.
Laravel ORCID validation rule - see: https://learntech.imsu.ox.ac.uk/blog/angular-reactive-form-custom-validator-for-orcid/
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 | |
namespace App\Rules; | |
use Illuminate\Contracts\Validation\Rule; | |
class Orcid implements Rule | |
{ | |
/** | |
* Create a new rule instance. | |
* | |
* @return void | |
*/ | |
public function __construct() | |
{ | |
// | |
} | |
/** | |
* Determine if the validation rule passes. | |
* | |
* @param string $attribute | |
* @param mixed $value | |
* @return bool | |
*/ | |
public function passes($attribute, $value) | |
{ | |
$urlParts = explode("/",$value); | |
// get last digit | |
$lastDigit = substr($urlParts[count($urlParts) - 1],-1); | |
// let's get numbers from last part (removing any hyphens, etc) | |
$orcidDigits = preg_replace('/\D/', '', $urlParts[count($urlParts) - 1]); | |
// strip last digit | |
$baseDigits = substr($orcidDigits, 0, -1); | |
// get check digit - 0-9 or X | |
$generatedCheckDigit = $this->generateCheckDigit($baseDigits); | |
return $generatedCheckDigit === $lastDigit; | |
} | |
/** | |
* Get the validation error message. | |
* | |
* @return string | |
*/ | |
public function message() | |
{ | |
return 'The 16-digit number in the ORCID ID must have the correct checksum - please check it carefully'; | |
} | |
/** | |
* Generates check digit as per ISO 7064 11,2 - see https://support.orcid.org/knowledgebase/articles/116780-structure-of-the-orcid-identifier | |
* | |
*/ | |
private function generateCheckDigit($baseDigits) { | |
$total = 0; | |
for ($i = 0; $i < strlen($baseDigits); $i++) { | |
$digit = intval(substr($baseDigits,$i,1)); | |
$total = ($total + $digit) * 2; | |
} | |
$remainder = $total % 11; | |
$result = (12 - $remainder) % 11; | |
if($result == 10) { | |
return "X"; | |
} else { | |
return strval($result); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment