Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 965
smith Avatar asked Apr 27 '26 15:04

smith


1 Answers

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;
like image 173
amon Avatar answered Apr 29 '26 13:04

amon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!