Drupal 9 check if UUD is valid
In Drupal 9, you can check if a UUID (Universally Unique Identifier) is valid by using the Drupal::service()
method to access the uuid
service. The isValid()
method of the UuidInterface
class can then be used to validate the UUID.
Here is an example of how you can check if a UUID is valid in Drupal 9:
use Drupal\Component\Uuid\UuidInterface;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class MyService implements ContainerInjectionInterface {
protected $uuidService;
public function __construct(UuidInterface $uuidService) {
$this->uuidService = $uuidService;
}
public static function create(ContainerInterface $container) {
return new static(
$container->get('uuid')
);
}
public function isValidUuid($uuid) {
return $this->uuidService->isValid($uuid);
}
}
// Usage
$myService = \Drupal::service('my_service');
$uuid = '123e4567-e89b-12d3-a456-426614174000';
if ($myService->isValidUuid($uuid)) {
// The UUID is valid.
}
else {
// The UUID is not valid.
}
In the above example, we create a service called MyService
that takes the uuid
service as a dependency. We then define a method isValidUuid()
that accepts a UUID as a parameter and uses the isValid()
method of the UuidInterface
class to validate the UUID.
You can use this service in your code by injecting it as a dependency or by accessing it via the \Drupal::service()
method. Once you have an instance of the service, you can call the isValidUuid()
method to check if a UUID is valid.
Note that the example code assumes you have the necessary dependencies and service definitions in place. You may need to adjust the code to fit your specific Drupal setup.