Created
November 30, 2021 23:28
-
-
Save OscarKolsrud/5386e67a67c12ecd3b6c58921b8e0456 to your computer and use it in GitHub Desktop.
Laravel validation rule to check if a business ID (organisasjonsnummer) is valid against the national registry
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; | |
use Illuminate\Support\Facades\Http; | |
class ValidNorwegianOrganisation implements Rule | |
{ | |
/** | |
* Variable to store error message | |
*/ | |
protected $message; | |
/** | |
* 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) | |
{ | |
if (strlen($value) == 9 && is_numeric($value)) { | |
$response = Http::get('https://data.brreg.no/enhetsregisteret/api/enheter/' . $value); | |
if ($response->successful()) { | |
//Process the request from BRREG, if there is a business set all is probaly good | |
if ((isset($response->json()["navn"]))) { | |
return true; | |
} else { | |
$this->message = "Brønnøysundregistrene returnerte et uventet resultat"; | |
return false; | |
} | |
} elseif ($response->clientError()) { | |
//Request to BRREG failed due to a network, server or similar error | |
$this->message = "Fant ingen bedrift med organisasjonsnummer " . $value; | |
return false; | |
} else { | |
//Request to BRREG failed due to a network, server or similar error | |
$this->message = "Feil: Forespørselen mot Brønnøysundregistrene feilet"; | |
return false; | |
} | |
} else { | |
//Failed basic validation | |
$this->message = "Organisasjonsnummeret må være 9 siffer uten mellomrom"; | |
return false; | |
} | |
} | |
/** | |
* Get the validation error message. | |
* | |
* @return string | |
*/ | |
public function message() | |
{ | |
return $this->message; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment