[erlang-questions] Idiomatically handling multiple validation checks

Dmytro Lytovchenko <>
Tue Dec 6 10:13:34 CET 2016


For things like web form or input validation and transformation, it is
often a good idea to make a chain of nested calls.

Imagine your user submitted a form which you store in Data = #{login="",
password=""}, you can do something like this:

try
    create_session(check_password(check_login(Data)))
catch throw:{validation_error, E} -> my_report_error(E)
end,...


Here each function (check_login, check_password, create_session) takes
result of the previous function, it can be that same Data, or Data paired
with some intermediate results if you wish. To signal an error you use
erlang:throw({validation_error, "my error"}) and it will be caught in the
catch clause.

2016-12-06 0:16 GMT+01:00 qp <>:

> Hi, I am new to Erlang and wrote this code for validating that the Name,
> Action & Target atoms passed in to validRequest are all valid.
>
> validRequest(valid, valid, Target) ->
>   case validName(Target) of
>       true -> true;
>       false -> false
>   end;
> validRequest(valid, Action, Target) ->
>   case validAction(Action) of
>       true -> validRequest(valid, valid, Target);
>       false -> false
>   end;
> validRequest(Name, Action, Target) ->
>   case validName(Name) of
>       true -> validRequest(valid, Action, Target);
>       false -> false
>   end.
>
> I've since refactored into
>
> validRequest(Name, Action, Target) ->
>   validName(Name) and validAction(Action) and validName(Target).
>
> I'm curious what a more idiomatic way of writing this would be? I've seen
> a mix of styles using booleans for return values and tuples, with errors
> listed. I don't think that's needed here but I'm just curious how you would
> handle multiple validation checks, especially if they were more complicated
> than this example. Thank you!
>
> _______________________________________________
> erlang-questions mailing list
> 
> http://erlang.org/mailman/listinfo/erlang-questions
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20161206/2fc6a9ff/attachment.html>


More information about the erlang-questions mailing list