Search code examples
perlmojoliciousmojolicious-lite

Mojolicious Parameter Validation


I have the following code :

get '/:foo' => sub {
  my $c   = shift;
  my $v = $c->validation;
  
  my $foo = $c->param('y');
  $c->render(text => "Hello from $foo.") if  $v->required('y')->like(q/[A-Z]/);
};

and want to verify the y parameter of the http request I connect to the above web page using: http://myserver:3000?x=2&y=1

It prints Hello from 1. Even though there is $v->required('y')->like(q/[A-Z]/);

What could be my problem here?


Solution

  • Mojolicious validation uses a fluent interface, so most methods return the validation object. Objects are truthy by default, so your condition is always true.

    Instead, you can check

    • ->is_valid() – whether validation for the current topic was sucessful, or
    • ->has_error() – whether there were any validation errors.

    You introduce a new validation topic by calling ->required('name') or ->optional('name') on the validation object. So you could write:

    $c->render(text => "Hello from $foo.")
      if $v->required('y')->like(q/[A-Z]/)->is_valid;
    

    or

    $v->required('y')->like(q/[A-Z]/);
    $c->render(text => "Hello from $foo.") unless $v->has_error;