Is it possible to write a guard clause that validates a regex?

Hi,

I am currently trying to implement a guard which validates that a parameter is a valid URL. Is it possible to call URI.parse or Regex.match inside a guard clause? I am a newbie that is learning Elixir, and maybe I totally misunderstand guards.

Cheers
Oliver

Hello and welcome,

Unfortunately, it’s not… You can see this at the top of this document.

From the doc.

Not all expressions are allowed in guard clauses, but only a handful of them. This is a deliberate choice. This way, Elixir (and Erlang) can make sure that nothing bad happens while executing guards and no mutations happen anywhere. It also allows the compiler to optimize the code related to guards efficiently.

https://hexdocs.pm/elixir/guards.html#defining-custom-guard-expressions

You could call a function with the result of Uri.parse for example, this way You could pattern match the result.

3 Likes

In addition to what @kokolegorille said, it is perfectly valid and possible to have Erlang installation without re module. This would be hard to have guards to be dependant on external libraries.

2 Likes

One of the main reasons for this is if you could have an arbitrary function in a guard clause it could have some side effect when run, which would happen even if that function clause should not be run. In haskell you can prevent this but not in Erlang/Elixir

1 Like

Best you can do is validate that the string starts with “http://” or “https://”, and then match the hostname to a whitelist.

2 Likes