Skip to content

Instantly share code, notes, and snippets.

@OscarKolsrud
Created November 30, 2021 23:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save OscarKolsrud/5386e67a67c12ecd3b6c58921b8e0456 to your computer and use it in GitHub Desktop.
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
<?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