Created
November 5, 2011 00:26
-
-
Save Deepwalker/1340863 to your computer and use it in GitHub Desktop.
Small erlang data validator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-module(validate). | |
-compile(export_all). | |
list_to_number(L) -> | |
try list_to_float(L) | |
catch | |
error:badarg -> list_to_integer(L) | |
end. | |
% Functions for checking proplists from wild and convert it | |
check_string(RawString) -> | |
RawString. | |
check_date(RawDateTime) -> | |
DateTime = dh_date:parse(RawDateTime), | |
case DateTime of | |
{error, _} -> | |
false; | |
DT -> | |
DT | |
end. | |
check_number(RawString) -> | |
try list_to_number(RawString) | |
catch | |
error:badarg -> false | |
end. | |
% AtomsList -> [true, false, ...] | |
% You cant use it in your code directly - you must to define your own validator | |
% like fun(Value) -> utils:check_atom(Value, [day, month, week, year]) end. | |
check_atom(RawString, AtomsList) -> | |
try lists:member(erlang:list_to_atom(RawString), AtomsList) of | |
false -> false; | |
true -> erlang:list_to_atom(RawString) | |
catch | |
error:badarg -> false | |
end. | |
% We use `check_param` func that return value or `false`. | |
% then we check for Keys that get `false` from validator | |
% If there is any Keys with false - we return {error, list of this keys}. | |
% Else proplist with parsed data | |
% Result list sorted for pattern matching | |
check_params(Params, Validators) -> | |
Checked = lists:map(fun({Key, Validator}) -> {Key, check_param(Key, Validator, Params)} end, Validators), | |
Errors = [Key || {Key, false} <- Checked], | |
case Errors of | |
[] -> lists:sort(Checked); | |
_ -> {error, Errors} | |
end. | |
check_param(Key, Validator, Params) -> | |
case proplists:get_value(Key, Params) of | |
undefined -> | |
false; | |
Value -> | |
Validator(Value) | |
end. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment