Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 605
Marco C. Stewart Avatar asked Nov 18 '25 11:11

Marco C. Stewart


1 Answers

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

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

It will return:

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

EDIT

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

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

{:ok, "38cd0012-79dc-4838-acc0-94d4143c4f2c"}
like image 95
Kociamber Avatar answered Nov 20 '25 01:11

Kociamber



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!