Is it possible to avoid repetitive validation code?

42 views
Skip to first unread message

Michael Fung

unread,
Feb 26, 2018, 11:08:23 PM2/26/18
to Mojolicious
Hi All,

I am trying out Mojolicious::Validator. It is very elegant. But, if many actions take a optional "page" parameter, then I need to include something like the following for all these actions.

sub action1 {
 
...

  $validation
->optional('page')->num(1,100);


Is there a way to avoid this repetition while using Mojolicious::Validator?


Thanks,
Michael



Jan Henning Thorsen

unread,
Feb 27, 2018, 1:48:36 PM2/27/18
to Mojolicious
Yes. Put it in a helper:

$app->helper("validate.page" => sub { shift->validaton->optional('page')->num(1, 100) })

and use it as:

$c->validate->page;

Or you could also route condition or a "under route" where you add the validation before your action is called:

Michael Fung

unread,
Feb 27, 2018, 10:02:33 PM2/27/18
to Mojolicious
Hi Jan, thanks! I will borrow the concept and try to make it works like:

sub action1 {
 
...
  $c
->check_required(qw/node token/);
  $c
->check_optional(qw/page/);


Reply all
Reply to author
Forward
0 new messages