[Idea] A more generic validation function

5 views
Skip to first unread message

Dmitrii Dimandt

unread,
Apr 23, 2008, 11:57:08 AM4/23/08
to erl...@googlegroups.com
Yup, it's me again :) Minor improvements to the function

Same stuff. Create a form that contains 4 fields:
- login
- password
- password_repeat
- email

and the following validation function:
process_signup(A) ->
F = fun(A, Field) ->
{ok, Val} = yaws_api:postvar(A, Field),
L = string:len(Val),
if
L < 4 orelse L > 16 ->
{Field, {length}};
true ->
{}
end
end,
EmailCheck = fun(Args, Field2) ->
{ok, Email} = yaws_api:postvar(Args, Field2),
Match = regexp:match(Email, "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-
Za-z]+"),
Match /= nomatch
end,

%% the magic is here :)
buktu_form:validate(A, [
{login, [F, {'=', "User"}]},
{email, EmailCheck},
{password, [{'=', password_repeat}, F, {'=', "Password"}]}
]).


Couple of notes:
- the function that you pass in can return:
-- a tuple in the form {FieldName, Error}
-- true if validation succeeded, false if validation failed
-- arbitrary Value which will be converted to {FieldName, Value}

- if any of the fields in the rule don't exist or are empty, for each
such rule the function will return
-- {invalid_field} if you match the field against a value
-- {invalid_fields, [field1, field2]} if you match the field against
another field

- You can pass several rules to a fild, just organize them in a list.
If you only need one rule, you don't need a list. If you only need to
check for a field's existence, pass in a tuple that contains only the
field's name:
- {field_name} %% check if the field exists
- {field_name, {'=', field2_name}} %% check if the field is equal to
another field
- {field_name, {'=', Value}} %% check if the field is equal to a value
- {field_name, F} %% pass in a callback
You can pass '=', '/=', '<', '=<', '>', '>=' as rules for simple matches


The entire return value of the function is a proplist in the form
[{FieldName, Errors}] where Errorrs = Error | [Error]


buktu_form.erl
Reply all
Reply to author
Forward
0 new messages