Marco C. Stewart
Marco C. Stewart

Reputation: 185

How to check whether a string is a valid UUID?

I'm using Phoenix and Ecto. In a model I have a UUID field. In some cases I'll need to check whether a string that comes from a user is a proper UUID. How to do it?

I've checked out https://hexdocs.pm/ecto/Ecto.UUID.html but based on the decription I haven't found a proper function that appears to be the one I'd use in my case.

How to do it?

Upvotes: 2

Views: 3331

Answers (2)

Kociamber
Kociamber

Reputation: 1155

If you are using UUID dep you can check it with UUID.info/1 function, ie:

UUID.info("58b784e4-a3cd-4880-8629-a481f017c4c")

Will return:

{:error, "Invalid argument; Not a valid UUID: 58b784e4-a3cd-4880-8629-a481f017c4c"}

EDIT

Another option would be using Ecto.UUID.cast/1 and below patternmatching:

iex(2)> Ecto.UUID.cast "38cd0012-79dc-4838-acc0-94d4143c4f2c"

{:ok, "38cd0012-79dc-4838-acc0-94d4143c4f2c"}

Upvotes: 4

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121010

Ecto itself would use dump/1 to convert to the native type.

cast/1 suggested by @Daniel is almost what you need, but it’d accept raw UUID as well, what, as I understood from the task description, is not expected.

That said, match?({:ok, _}, Ecto.UUID.dump(input)) is your friend here.

Upvotes: 2

Related Questions