yii2 数字最大值、最小值,带点和逗号验证

问题描述 投票:0回答:1

在我的脚本中,我需要使用逗号和点以及最大值和最小值验证价格。 这是我的规则()

return [
        [['price'], 'required', 'message' => 'Price ...'],
        [['price'], 'number', 'numberPattern' => '/^[0-9]{1,2}([\.,][0-9]{1,2})*$/',
            'message' => 'Price ...', 'max' => 25, min => '0'],
    ];

当我将价格设置为 25.00(. 点)时,效果很好,但当我设置 25,01(,逗号)时,验证不起作用。你知道如何让它发挥作用吗?

php validation yii2
1个回答
1
投票

我发现这个解决方案适用于所有输入,您不需要寻找特定的小部件选项。在您的 View 文件(首选底部)中注册 JS:

$this->registerJs("        
    $(document).ready(function() {
        $(document).on('keyup', 'input', function(e){
            $(this).val($(this).val().replace(/[,]/g, '.'));
        });
    });
");

这会将所有输入中的所有逗号更改为。我已经测试过自己(当然)并且效果很好。

但是,如果您想以“仅在某些输入中应用”的方式进行更改,则必须为每个输入添加一个自定义类,然后将此代码稍微更改为: $this->registerJs(" $(document).ready(function() { $(document).on('keyup', '.CustomClassName', function(e){ $(this).val($(this).val().replace(/[,]/g, '.')); }); }); ");

我认为这比使用小部件选项更好,因为您将需要找到这样一个选项(您甚至不知道这个选项是否存在),而只要您不忘记,这个选项将始终存在添加自定义类并注册此 JavaScript 代码。

© www.soinside.com 2019 - 2024. All rights reserved.