Yii2数字的最大值,最小值与点和逗号验证


yii2 number max, min with dot and comma validation

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

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

当我把价格定为25美元时,效果很好。点),但当我输入25,01(,逗号)验证不起作用。你知道怎么做吗?

我发现这个解决方案可以很好地处理所有输入,您不需要寻找特定的小部件选项。在你的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代码。