Check if String is Valid UUID using PHP

ramsey/uuid library

  1. Add ramsey/uuid library to composer.json file:
"require": {
    "ramsey/uuid": "^4.1"
}
  1. Install library from the command line:
composer install
  1. Check if a string is valid UUID:
<?php

use Ramsey\Uuid\Nonstandard\Uuid;

require_once __DIR__.'/vendor/autoload.php';

function isValidUuid(string $value): bool
{
    return Uuid::isValid($value);
}

$isValid = isValidUuid('5338d5e4-6f3e-45fe-8af5-e2d96213b3f0');
echo (int) $isValid; // 1

$isValid = isValidUuid('xx38d5e4-6f3e-45fe-8af5-e2d96213b3f0');
echo (int) $isValid; // 0

Leave a Comment

Cancel reply

Your email address will not be published.