Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if a string is a valid v4 UUID? [duplicate]

Tags:

regex

php

uuid

I'm making a validator based on UUID generated by client browser, I use this to identify a certain type data that the user sends; and would like to validate that the UUID that client sends it is in fact a valid Version 4 UUID.

I found this PHP preg_match UUID v4, it's close but not exactly what I'm looking for. I wish to know if exists something similar to is_empty() or strtodate() Where if string is not valid Sends FALSE.

I could do based on the regular expression but I would like something more native to test it.

Any ideas?

11/23/2019 EDIT: About the duplicate tag, while the moderator is technicallly correct, this question was formulated with the goal of fibd something else to regex if existed, and in second place this question has become a reference to Pythoners and PHPers and has a different answers/approach to solve the problem and their answers are better explained in general. This is why I consider this question should be perserved

like image 343
Rafael Avatar asked Nov 14 '13 22:11

Rafael


People also ask

How do you check if a string is a valid UUID?

A valid UUID should have 5 sections separated by a dash ( - ) and in the first section it should have 8 characters, the second, third, and the fourth section should have 4 characters each, and the last section should have 12 characters with a total of 32 characters.

Is uuidv4 a string?

UUID. bytes. The UUID as a 16-byte string (containing the six integer fields in big-endian byte order).

What is a valid UUID format?

Format. In its canonical textual representation, the 16 octets of a UUID are represented as 32 hexadecimal (base-16) digits, displayed in five groups separated by hyphens, in the form 8-4-4-4-12 for a total of 36 characters (32 hexadecimal characters and 4 hyphens). For example: 123e4567-e89b-12d3-a456-426614174000.

Is string a UUID Java?

Description. The fromString(String name) method is used to create a UUID from the string standard representation as described in the toString() method.


1 Answers

Version 4 UUIDs have the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx where x is any hexadecimal digit and y is one of 8, 9, A, or B.

^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$ 

To allow lowercase letters, use i modifier →

$UUIDv4 = '/^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i'; preg_match($UUIDv4, $value) or die('Not valid UUID'); 
like image 135
Ωmega Avatar answered Oct 01 '22 18:10

Ωmega