/modules/mod_base/validators/validator_base_length.erl

https://code.google.com/p/zotonic/ · Erlang · 48 lines · 24 code · 6 blank · 18 comment · 2 complexity · 647c8dd4303f71e8e41ad83a1a3e59b2 MD5 · raw file

  1. %% @author Marc Worrell <marc@worrell.nl>
  2. %% @copyright 2009 Marc Worrell
  3. %% @doc Validator for checking if an input value is within a certain length range
  4. %% Copyright 2009 Marc Worrell
  5. %%
  6. %% Licensed under the Apache License, Version 2.0 (the "License");
  7. %% you may not use this file except in compliance with the License.
  8. %% You may obtain a copy of the License at
  9. %%
  10. %% http://www.apache.org/licenses/LICENSE-2.0
  11. %%
  12. %% Unless required by applicable law or agreed to in writing, software
  13. %% distributed under the License is distributed on an "AS IS" BASIS,
  14. %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. %% See the License for the specific language governing permissions and
  16. %% limitations under the License.
  17. -module(validator_base_length).
  18. -include("zotonic.hrl").
  19. -export([render_validator/5, validate/5]).
  20. render_validator(length, TriggerId, _TargetId, Args, Context) ->
  21. Min = proplists:get_value(minimum, Args),
  22. Max = proplists:get_value(maximum, Args),
  23. JsObject = z_utils:js_object(z_validation:rename_args(Args)),
  24. Script = [<<"z_add_validator(\"">>,TriggerId,<<"\", \"length\", ">>, JsObject, <<");\n">>],
  25. {[to_number(Min),to_number(Max)], Script, Context}.
  26. %% @spec validate(Type, TriggerId, Values, Args, Context) -> {ok,AcceptedValue} | {error,Id,Error}
  27. %% Error = invalid | novalue | {script, Script}
  28. validate(length, Id, Value, [Min,Max], Context) ->
  29. Len = length(Value),
  30. MinOK = (Min == -1 orelse Len >= Min),
  31. MaxOK = (Max == -1 orelse Len =< Max),
  32. case MinOK andalso MaxOK of
  33. true -> {{ok, Value}, Context};
  34. false -> {{error, Id, invalid}, Context}
  35. end.
  36. to_number(undefined) ->
  37. -1;
  38. to_number(N) when is_integer(N) ->
  39. N;
  40. to_number(N) ->
  41. {I,_Rest} = string:to_integer(N),
  42. I.