PageRenderTime 8ms CodeModel.GetById 1ms app.highlight 4ms RepoModel.GetById 1ms app.codeStats 0ms

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