You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mojolicious参数验证异常:不符合正则规则的参数仍通过验证

Why Your Mojolicious Validation Isn't Working

Let's break down why your validation logic isn't blocking the invalid y=1 parameter:

The Core Issue

Your if condition is checking the wrong thing. In Mojolicious, every method in the Validation chain (like required() or like()) returns the Validation object itself, not a boolean indicating success or failure. In Perl, any non-empty object evaluates to true in a boolean context—so your if block will always run, no matter if the validation passes or fails.

That's why even when y=1 (which doesn't match [A-Z]) your code still renders the "Hello from 1" message.

How to Fix It

You need to explicitly check if the validation for y passed using either is_valid() or has_error() on the Validation object. Here's the corrected code:

get '/:foo' => sub { 
    my $c = shift; 
    my $v = $c->validation; 

    # Define your validation rules first
    $v->required('y')->like(qr/[A-Z]/); # Using qr// is more idiomatic for regexes in Perl

    # Check if the validation passed for 'y'
    if ($v->is_valid('y')) {
        my $foo = $c->param('y'); 
        $c->render(text => "Hello from $foo.");
    } else {
        # Handle validation failure (e.g., return an error response)
        $c->render(
            text   => 'Error: Parameter "y" must be an uppercase letter (A-Z)',
            status => 400 # Bad Request status code is appropriate here
        );
    }
};

A Quick Side Note

Your route uses /:foo (a path parameter), but you're accessing the query parameter y with $c->param('y'). The :foo path parameter isn't being used in your current code—if that's intentional, great! If not, you might want to adjust either the route or how you access the parameter.

内容的提问来源于stack exchange,提问作者smith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:00:37