Validate UUID with Laravel Validation

Laravel 5.6 provides the ramesey/uuid package out of the box now. You can use its "isValid" method now to check for a UUID. I noticed that the regex in the solution above would fail sometimes. I haven't had any issue yet with the package used by Laravel internally.

Validator::extend('uuid', function ($attribute, $value, $parameters, $validator) {
    return \Ramsey\Uuid\Uuid::isValid($value);
});

Unrelated to the question but you can now also generate a UUID using the "Str" class from Laravel. It is the reason why ramsey/uuid is now included by default, removing the necessity to include your own regex.

\Illuminate\Support\Str::uuid();

You can extend the validator helper in Laravel to add your custom validation rules, for example I've created my own validation rule to validate location using regex as follow:

Validator::extend('location', function ($attribute, $value, $parameters, $validator) {
    return preg_match('/^-?\d{1,2}\.\d{6,}\s*,\s*-?\d{1,2}\.\d{6,}$/', $value);
});

Referencing this post: PHP preg_match UUID v4

You can the use UUID regex to create it as follows:

Validator::extend('uuid', function ($attribute, $value, $parameters, $validator) {
    return preg_match('/[a-f0-9]{8}\-[a-f0-9]{4}\-4[a-f0-9]{3}\-(8|9|a|b)[a-f0-9]{3‌​}\-[a-f0-9]{12}/', $value);
});

Hope that this match your request.


Actually, Laravel 5.7 supports UUID validation.

$validation = $this->validate($request, [
    'uuid_field' => 'uuid'
]);

Based on documentation.